"""Platform for switch integration."""

import asyncio
from typing import Any, override

from smarttub import SpaPump

from homeassistant.components.switch import SwitchEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator

from .const import API_TIMEOUT, ATTR_PUMPS
from .controller import SmartTubConfigEntry
from .entity import SmartTubEntity

PARALLEL_UPDATES = 0


async def async_setup_entry(
    hass: HomeAssistant,
    entry: SmartTubConfigEntry,
    async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
    """Set up switch entities for the pumps on the tub."""

    controller = entry.runtime_data

    entities = [
        SmartTubPump(controller.coordinator, pump)
        for spa in controller.spas
        for pump in controller.coordinator.data[spa.id][ATTR_PUMPS].values()
    ]

    async_add_entities(entities)


class SmartTubPump(SmartTubEntity, SwitchEntity):
    """A pump on a spa."""

    def __init__(
        self, coordinator: DataUpdateCoordinator[dict[str, Any]], pump: SpaPump
    ) -> None:
        """Initialize the entity."""
        super().__init__(coordinator, pump.spa, "pump")
        self.pump_id = pump.id
        self.pump_type = pump.type
        self._attr_unique_id = f"{super().unique_id}-{pump.id}"
        if pump.type == SpaPump.PumpType.CIRCULATION:
            self._attr_translation_key = "circulation_pump"
        elif pump.type == SpaPump.PumpType.JET:
            self._attr_translation_key = "jet"
            self._attr_translation_placeholders = {"pump_id": str(pump.id)}
        else:
            self._attr_translation_key = "pump"
            self._attr_translation_placeholders = {"pump_id": str(pump.id)}

    @property
    def pump(self) -> SpaPump:
        """Return the underlying SpaPump object for this entity."""
        return self.coordinator.data[self.spa.id][ATTR_PUMPS][self.pump_id]

    @property
    @override
    def is_on(self) -> bool:
        """Return True if the pump is on."""
        return self.pump.state != SpaPump.PumpState.OFF

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

        # the API only supports toggling
        if not self.is_on:
            await self.async_toggle()

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

        # the API only supports toggling
        if self.is_on:
            await self.async_toggle()

    @override
    async def async_toggle(self, **kwargs: Any) -> None:
        """Toggle the pump on or off."""
        async with asyncio.timeout(API_TIMEOUT):
            await self.pump.toggle()
        await self.coordinator.async_request_refresh()
