"""The Coolmaster integration."""

from pycoolmasternet_async import CoolMasterNet

from homeassistant.const import CONF_HOST, CONF_PORT, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import device_registry as dr

from .const import CONF_SEND_WAKEUP_PROMPT, CONF_SWING_SUPPORT, DOMAIN
from .coordinator import CoolmasterConfigEntry, CoolmasterDataUpdateCoordinator

PLATFORMS = [Platform.BINARY_SENSOR, Platform.BUTTON, Platform.CLIMATE, Platform.SENSOR]


async def async_setup_entry(hass: HomeAssistant, entry: CoolmasterConfigEntry) -> bool:
    """Set up Coolmaster from a config entry."""
    host = entry.data[CONF_HOST]
    port = entry.data[CONF_PORT]
    send_wakeup_prompt = entry.data.get(CONF_SEND_WAKEUP_PROMPT, False)
    if not entry.data.get(CONF_SWING_SUPPORT):
        coolmaster = CoolMasterNet(
            host,
            port,
            send_initial_line_feed=send_wakeup_prompt,
        )
    else:
        # Swing support adds an additional request per unit. The requests are
        # done in parallel, which can cause delays on the server. Therefore,
        # we increase the request timeout to 5 seconds instead of 1.
        coolmaster = CoolMasterNet(
            host,
            port,
            send_initial_line_feed=send_wakeup_prompt,
            read_timeout=5,
            swing_support=True,
        )
    try:
        info = await coolmaster.info()
        if not info:
            raise ConfigEntryNotReady
    except OSError as error:
        raise ConfigEntryNotReady from error
    coordinator = CoolmasterDataUpdateCoordinator(hass, entry, coolmaster, info)
    await coordinator.async_config_entry_first_refresh()
    entry.runtime_data = coordinator
    await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)

    return True


async def async_unload_entry(hass: HomeAssistant, entry: CoolmasterConfigEntry) -> bool:
    """Unload a Coolmaster config entry."""
    return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)


async def async_remove_config_entry_device(
    hass: HomeAssistant,
    config_entry: CoolmasterConfigEntry,
    device_entry: dr.DeviceEntry,
) -> bool:
    """Remove a config entry from a device."""
    return not device_entry.identifiers.intersection(
        (DOMAIN, unit_id) for unit_id in config_entry.runtime_data.data
    )
