"""Support for Vodafone Station routers."""

from typing import override

from homeassistant.components.device_tracker import ScannerEntity
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from .const import LOGGER
from .coordinator import (
    VodafoneConfigEntry,
    VodafoneStationDeviceInfo,
    VodafoneStationRouter,
)

# Coordinator is used to centralize the data updates
PARALLEL_UPDATES = 0


async def async_setup_entry(
    hass: HomeAssistant,
    entry: VodafoneConfigEntry,
    async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
    """Set up device tracker for Vodafone Station component."""

    LOGGER.debug("Start device trackers setup")
    coordinator = entry.runtime_data

    tracked: set = set()

    @callback
    def async_update_router() -> None:
        """Update the values of the router."""
        async_add_new_tracked_entities(coordinator, async_add_entities, tracked)

    entry.async_on_unload(
        async_dispatcher_connect(
            hass, coordinator.signal_device_new, async_update_router
        )
    )

    async_update_router()


@callback
def async_add_new_tracked_entities(
    coordinator: VodafoneStationRouter,
    async_add_entities: AddConfigEntryEntitiesCallback,
    tracked: set[str],
) -> None:
    """Add new tracker entities from the router."""
    new_tracked = []

    LOGGER.debug("Adding device trackers entities")
    for mac, device_info in coordinator.data.devices.items():
        if mac in tracked:
            continue
        LOGGER.debug("New device tracker: %s", device_info.device.name)
        new_tracked.append(VodafoneStationTracker(coordinator, device_info))
        tracked.add(mac)

    async_add_entities(new_tracked)


class VodafoneStationTracker(CoordinatorEntity[VodafoneStationRouter], ScannerEntity):
    """Representation of a Vodafone Station device."""

    _attr_translation_key = "device_tracker"
    _attr_has_entity_name = True
    mac_address: str

    def __init__(
        self, coordinator: VodafoneStationRouter, device_info: VodafoneStationDeviceInfo
    ) -> None:
        """Initialize a Vodafone Station device."""
        super().__init__(coordinator)
        self._coordinator = coordinator
        mac = device_info.device.mac
        self._attr_mac_address = mac
        self._attr_unique_id = mac
        self._attr_hostname = self._attr_name = device_info.device.name or mac.replace(
            ":", "_"
        )

    @property
    def _device_info(self) -> VodafoneStationDeviceInfo:
        """Return fresh data for the device."""
        return self.coordinator.data.devices[self.mac_address]

    @property
    @override
    def is_connected(self) -> bool:
        """Return true if the device is connected to the network."""
        return self._device_info.home

    @property
    @override
    def ip_address(self) -> str | None:
        """Return the primary ip address of the device."""
        return self._device_info.device.ip_address
