## pylint: disable=unused-argument

""" Implements the VersatileThermostat select component """
import logging
from vtherm_api.log_collector import get_vtherm_logger
from typing import Any

from homeassistant.core import HomeAssistant, callback

from homeassistant.const import EntityCategory
from homeassistant.components.switch import SwitchEntity

from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from .base_entity import VersatileThermostatBaseEntity

from .const import *  # pylint: disable=unused-wildcard-import,wildcard-import

_LOGGER = get_vtherm_logger(__name__)


async def async_setup_entry(
    hass: HomeAssistant,
    entry: ConfigEntry,
    async_add_entities: AddEntitiesCallback,
) -> None:
    """Set up the VersatileThermostat switches with config flow."""
    unique_id = entry.entry_id
    name = entry.data.get(CONF_NAME)
    _LOGGER.debug("%s - Calling async_setup_entry entry=%s, data=%s", name, entry.entry_id, entry.data)

    vt_type = entry.data.get(CONF_THERMOSTAT_TYPE)
    auto_start_stop_feature = entry.data.get(CONF_USE_AUTO_START_STOP_FEATURE)

    entities = []
    if vt_type == CONF_THERMOSTAT_CLIMATE:
        entities.append(FollowUnderlyingTemperatureChange(hass, unique_id, name, entry))

        if auto_start_stop_feature is True:
            # Creates a switch to enable the auto-start/stop
            enable_entity = AutoStartStopEnable(hass, unique_id, name, entry)
            entities.append(enable_entity)

    async_add_entities(entities, True)


class AutoStartStopEnable(VersatileThermostatBaseEntity, SwitchEntity, RestoreEntity):
    """The that enables the ManagedDevice optimisation with"""

    def __init__(
        self, hass: HomeAssistant, unique_id: str, name: str, entry_infos: ConfigEntry
    ):
        super().__init__(hass, unique_id, name)
        self._attr_name = "Enable auto start/stop"
        self._attr_unique_id = f"{self._device_name}_enable_auto_start_stop"
        self._attr_entity_category = EntityCategory.CONFIG
        self._default_value = (
            entry_infos.data.get(CONF_AUTO_START_STOP_LEVEL)
            != AUTO_START_STOP_LEVEL_NONE
        )
        self._attr_is_on = self._default_value

    @property
    def icon(self) -> str | None:
        """The icon"""
        return "mdi:power-sleep"

    async def async_added_to_hass(self):
        await super().async_added_to_hass()

        # Récupérer le dernier état sauvegardé de l'entité
        last_state = await self.async_get_last_state()

        # Si l'état précédent existe, vous pouvez l'utiliser
        if last_state is not None:
            self._attr_is_on = last_state.state == "on"
        else:
            # If no previous state set it to false by default
            self._attr_is_on = self._default_value

        await self.update_my_state_and_vtherm()

    async def update_my_state_and_vtherm(self):
        """Update the auto_start_stop_enable flag in my VTherm"""
        self.async_write_ha_state()
        if (
            self.my_climate is not None
            and self.my_climate.auto_start_stop_manager is not None
        ):
            await self.my_climate.auto_start_stop_manager.set_auto_start_stop_enable(self._attr_is_on)

    @callback
    async def async_turn_on(self, **kwargs: Any) -> None:
        """Turn the entity on."""
        self._attr_is_on = True
        await self.update_my_state_and_vtherm()

    @callback
    async def async_turn_off(self, **kwargs: Any) -> None:
        """Turn the entity off."""
        self._attr_is_on = False
        await self.update_my_state_and_vtherm()

    @overrides
    def turn_off(self, **kwargs: Any):
        self.hass.create_task(self.async_turn_off(**kwargs))

    @overrides
    def turn_on(self, **kwargs: Any):
        self.hass.create_task(self.async_turn_on(**kwargs))


class FollowUnderlyingTemperatureChange(
    VersatileThermostatBaseEntity, SwitchEntity, RestoreEntity
):
    """The that enables the ManagedDevice optimisation with"""

    def __init__(
        self, hass: HomeAssistant, unique_id: str, name: str, entry_infos: ConfigEntry
    ):
        super().__init__(hass, unique_id, name)
        self._attr_name = "Follow underlying temp change"
        self._attr_unique_id = f"{self._device_name}_follow_underlying_temp_change"
        self._attr_is_on = False
        self._attr_entity_category = EntityCategory.CONFIG

    @property
    def icon(self) -> str | None:
        """The icon"""
        return "mdi:content-copy"

    async def async_added_to_hass(self):
        await super().async_added_to_hass()

        # Récupérer le dernier état sauvegardé de l'entité
        last_state = await self.async_get_last_state()

        # Si l'état précédent existe, vous pouvez l'utiliser
        if last_state is not None:
            self._attr_is_on = last_state.state == "on"
        else:
            # If no previous state set it to false by default
            self._attr_is_on = False

        self.update_my_state_and_vtherm()

    def update_my_state_and_vtherm(self):
        """Update the follow flag in my VTherm"""
        self.async_write_ha_state()
        if self.my_climate is not None:
            self.my_climate.set_follow_underlying_temp_change(self._attr_is_on)

    @callback
    async def async_turn_on(self, **kwargs: Any) -> None:
        """Turn the entity on."""
        self.turn_on()

    @callback
    async def async_turn_off(self, **kwargs: Any) -> None:
        """Turn the entity off."""
        self.turn_off()

    @overrides
    def turn_off(self, **kwargs: Any):
        self._attr_is_on = False
        self.update_my_state_and_vtherm()

    @overrides
    def turn_on(self, **kwargs: Any):
        self._attr_is_on = True
        self.update_my_state_and_vtherm()
