# 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 TwistButton(TwistModel):
    class ButtonEvent(Enum):
        PUSH = 0x00
        RELEASE = 0x01
        LONG_PUSH = 0x02
        LONG_RELEASE = 0x03
        DOUBLE_PUSH = 0x04
        DOUBLE_RELEASE = 0x05
        DOUBLE_LONG_PUSH = 0x06
        DOUBLE_LONG_RELEASE = 0x07

    def __init__(self, model_id: int, parent_device: TwistDevice):
        super().__init__(model_id, parent_device)
        self.last_event: TwistButton.ButtonEvent | None = None

    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]
                    # Store the event type
                    try:
                        self.last_event = TwistButton.ButtonEvent(value[0])
                    except ValueError:
                        self.last_event = None

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

    def print_context(self):
        event_name = self.last_event.name if self.last_event else "UNKNOWN"
        print(
            f"Button Device: {self.parent_device.twist_id}, Model: {self.model_id}, Last Event: {event_name}")
