# Copyright (C) 2025 Twist Innovation
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License for more details:
# https://www.gnu.org/licenses/gpl-3.0.html

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from TwistDevice import TwistDevice
from .TwistTypes import ContextErrors
from .TwistDevice import TwistModel
from enum import Enum


class TwistGarage(TwistModel):
    class EventIndexes(Enum):
        OPEN = 0x00
        CLOSE = 0x01
        TOGGLE = 0x02

    def __init__(self, model_id: int, parent_device: TwistDevice):
        super().__init__(model_id, parent_device)

    async def context_msg(self, payload: str):
        data = self.parse_general_context(payload)

        for ctx in data["cl"]:
            index, value = self._get_value_from_context(ctx)
            if index < ContextErrors.MAX.value:
                if ContextErrors(index) == ContextErrors.ACTUAL:
                    self.actual_state = value[0]

        if self._update_callback is not None:
            await self._update_callback(self)

    async def open(self):
        await self._activate_event(TwistGarage.EventIndexes.OPEN)

    async def close(self):
        await self._activate_event(TwistGarage.EventIndexes.CLOSE)

    async def toggle(self):
        await self._activate_event(TwistGarage.EventIndexes.TOGGLE)

    async def _activate_event(self, index: TwistGarage.EventIndexes):
        data = {
            "i": index.value,
            "vl": []
        }

        await self.parent_device.api.activate_event(self, data)

    def print_context(self):
        print(
            f"Garage Device: {self.parent_device.twist_id}, Model: {self.model_id}, Actual: {self.actual_state}")
