"""Support for the Xiaomi IR Remote (Chuangmi IR)."""
import asyncio
from datetime import timedelta
import logging
import time

from miio import ChuangmiIr, DeviceException  # pylint: disable=import-error
import voluptuous as vol

from homeassistant.components.remote import (
    ATTR_DELAY_SECS,
    ATTR_NUM_REPEATS,
    DEFAULT_DELAY_SECS,
    DOMAIN,
    PLATFORM_SCHEMA,
    RemoteDevice,
)
from homeassistant.const import (
    ATTR_ENTITY_ID,
    ATTR_HIDDEN,
    CONF_COMMAND,
    CONF_HOST,
    CONF_NAME,
    CONF_TIMEOUT,
    CONF_TOKEN,
)
from homeassistant.exceptions import PlatformNotReady
import homeassistant.helpers.config_validation as cv
from homeassistant.util.dt import utcnow

_LOGGER = logging.getLogger(__name__)

SERVICE_LEARN = "xiaomi_miio_learn_command"
DATA_KEY = "remote.xiaomi_miio"

CONF_SLOT = "slot"
CONF_COMMANDS = "commands"

DEFAULT_TIMEOUT = 10
DEFAULT_SLOT = 1

LEARN_COMMAND_SCHEMA = vol.Schema(
    {
        vol.Required(ATTR_ENTITY_ID): vol.All(str),
        vol.Optional(CONF_TIMEOUT, default=10): vol.All(int, vol.Range(min=0)),
        vol.Optional(CONF_SLOT, default=1): vol.All(int, vol.Range(min=1, max=1000000)),
    }
)

COMMAND_SCHEMA = vol.Schema(
    {vol.Required(CONF_COMMAND): vol.All(cv.ensure_list, [cv.string])}
)

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {
        vol.Optional(CONF_NAME): cv.string,
        vol.Required(CONF_HOST): cv.string,
        vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): vol.All(
            int, vol.Range(min=0)
        ),
        vol.Optional(CONF_SLOT, default=DEFAULT_SLOT): vol.All(
            int, vol.Range(min=1, max=1000000)
        ),
        vol.Optional(ATTR_HIDDEN, default=True): cv.boolean,
        vol.Required(CONF_TOKEN): vol.All(str, vol.Length(min=32, max=32)),
        vol.Optional(CONF_COMMANDS, default={}): cv.schema_with_slug_keys(
            COMMAND_SCHEMA
        ),
    },
    extra=vol.ALLOW_EXTRA,
)


async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
    """Set up the Xiaomi IR Remote (Chuangmi IR) platform."""
    host = config[CONF_HOST]
    token = config[CONF_TOKEN]

    # Create handler
    _LOGGER.info("Initializing with host %s (token %s...)", host, token[:5])

    # The Chuang Mi IR Remote Controller wants to be re-discovered every
    # 5 minutes. As long as polling is disabled the device should be
    # re-discovered (lazy_discover=False) in front of every command.
    device = ChuangmiIr(host, token, lazy_discover=False)

    # Check that we can communicate with device.
    try:
        device_info = await hass.async_add_executor_job(device.info)
        model = device_info.model
        unique_id = f"{model}-{device_info.mac_address}"
        _LOGGER.info(
            "%s %s %s detected",
            model,
            device_info.firmware_version,
            device_info.hardware_version,
        )
    except DeviceException as ex:
        _LOGGER.error("Device unavailable or token incorrect: %s", ex)
        raise PlatformNotReady

    if DATA_KEY not in hass.data:
        hass.data[DATA_KEY] = {}

    friendly_name = config.get(CONF_NAME, "xiaomi_miio_" + host.replace(".", "_"))
    slot = config.get(CONF_SLOT)
    timeout = config.get(CONF_TIMEOUT)

    hidden = config.get(ATTR_HIDDEN)

    xiaomi_miio_remote = XiaomiMiioRemote(
        friendly_name,
        device,
        unique_id,
        slot,
        timeout,
        hidden,
        config.get(CONF_COMMANDS),
    )

    hass.data[DATA_KEY][host] = xiaomi_miio_remote

    async_add_entities([xiaomi_miio_remote])

    async def async_service_handler(service):
        """Handle a learn command."""