from homeassistant.components.text import TextEntity, TextMode
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from .const import DOMAIN
from .coordinator import SmS4IoTCoordinator


async def async_setup_entry(
    hass: HomeAssistant,
    entry: ConfigEntry,
    async_add_entities: AddEntitiesCallback,
) -> None:
    coordinator: SmS4IoTCoordinator = hass.data[DOMAIN][entry.entry_id]
    async_add_entities(
        [
            SmS4IoTSSIDText(coordinator, entry),
            SmS4IoTFQDNText(coordinator, entry),
        ]
    )


class _SmS4IoTTextBase(CoordinatorEntity, TextEntity):
    """Base for write-only command text entities."""

    _attr_mode = TextMode.TEXT

    def __init__(self, coordinator: SmS4IoTCoordinator, entry: ConfigEntry) -> None:
        super().__init__(coordinator)
        self._last_sent: str = ""
        device_id = entry.data["device_id"]
        self._device_id = device_id
        self._attr_device_info = {
            "identifiers": {(DOMAIN, device_id)},
            "name": f"SMS4IoT {device_id}",
            "manufacturer": "SMS4IoT",
        }

    @property
    def native_value(self) -> str:
        return self._last_sent

    async def async_set_value(self, value: str) -> None:
        self._last_sent = value
        await self._send_command(value)
        self.async_write_ha_state()

    async def _send_command(self, value: str) -> None:
        raise NotImplementedError


class SmS4IoTSSIDText(_SmS4IoTTextBase):
    """Text entity that sends 'setwifi <ssid>' to the device."""

    def __init__(self, coordinator: SmS4IoTCoordinator, entry: ConfigEntry) -> None:
        super().__init__(coordinator, entry)
        self._attr_unique_id = f"{self._device_id}_set_ssid"
        self._attr_name = f"SMS4IoT {self._device_id} Set WiFi SSID"
        self._attr_icon = "mdi:wifi-settings"
        #self._attr_native_min = 1
        self._attr_native_max = 64

    async def _send_command(self, value: str) -> None:
        await self.coordinator.async_write_command(f"setwifi {value}")


class SmS4IoTFQDNText(_SmS4IoTTextBase):
    """Text entity that sends 'setdn <fqdn>' to the device."""

    def __init__(self, coordinator: SmS4IoTCoordinator, entry: ConfigEntry) -> None:
        super().__init__(coordinator, entry)
        self._attr_unique_id = f"{self._device_id}_set_fqdn"
        self._attr_name = f"SMS4IoT {self._device_id} Set FQDN"
        self._attr_icon = "mdi:domain"
        #self._attr_native_min = 1
        self._attr_native_max = 253

    async def _send_command(self, value: str) -> None:
        await self.coordinator.async_write_command(f"setdn {value}")

