from gateway_core.application.ports.RebootPort import RebootPort
from gateway_core.domain.Reboot import RebootDto, RebootType, RebootEntity
from gateway_core.domain.errors import NotSupportedError
from gateway_platform.systemd.SystemdManagerClient import SystemdManagerClient


class SystemdRebootPortAdapter(RebootPort):
    def __init__(
        self,
        *,
        systemd: SystemdManagerClient,
        unitName: str,
        isArmed: bool = False,
        allowedEntity: RebootEntity = RebootEntity.ecp,
        allowedType: RebootType = RebootType.soft,
    ) -> None:
        self.systemd = systemd
        self.unitName = unitName
        self.isArmed = isArmed
        self.allowedEntity = allowedEntity
        self.allowedType = allowedType

    async def triggerReboot(self, dto: RebootDto) -> None:
        if dto.entity != self.allowedEntity or dto.type != self.allowedType:
            raise NotSupportedError(
                f"systemd reboot supports only {self.allowedType}/{self.allowedEntity}"
            )

        if not self.isArmed:
            return

        await self.systemd.restartUnit(self.unitName)
