"""Support for Timers."""
from datetime import timedelta
import logging

import voluptuous as vol

from homeassistant.const import CONF_ICON, CONF_NAME
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.config_validation import ENTITY_SERVICE_SCHEMA
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.event import async_track_point_in_utc_time
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util

_LOGGER = logging.getLogger(__name__)

DOMAIN = "timer"
ENTITY_ID_FORMAT = DOMAIN + ".{}"

DEFAULT_DURATION = 0
ATTR_DURATION = "duration"
ATTR_REMAINING = "remaining"
CONF_DURATION = "duration"

STATUS_IDLE = "idle"
STATUS_ACTIVE = "active"
STATUS_PAUSED = "paused"

EVENT_TIMER_FINISHED = "timer.finished"
EVENT_TIMER_CANCELLED = "timer.cancelled"
EVENT_TIMER_STARTED = "timer.started"
EVENT_TIMER_RESTARTED = "timer.restarted"
EVENT_TIMER_PAUSED = "timer.paused"

SERVICE_START = "start"
SERVICE_PAUSE = "pause"
SERVICE_CANCEL = "cancel"
SERVICE_FINISH = "finish"

SERVICE_SCHEMA_DURATION = ENTITY_SERVICE_SCHEMA.extend(
    {vol.Optional(ATTR_DURATION, default=timedelta(DEFAULT_DURATION)): cv.time_period}
)

CONFIG_SCHEMA = vol.Schema(
    {
        DOMAIN: cv.schema_with_slug_keys(
            vol.Any(
                {
                    vol.Optional(CONF_NAME): cv.string,
                    vol.Optional(CONF_ICON): cv.icon,
                    vol.Optional(
                        CONF_DURATION, timedelta(DEFAULT_DURATION)
                    ): cv.time_period,
                },
                None,
            )
        )
    },
    extra=vol.ALLOW_EXTRA,
)


async def async_setup(hass, config):
    """Set up a timer."""
    component = EntityComponent(_LOGGER, DOMAIN, hass)

    entities = []

    for object_id, cfg in config[DOMAIN].items():
        if not cfg:
            cfg = {}

        name = cfg.get(CONF_NAME)
        icon = cfg.get(CONF_ICON)
        duration = cfg.get(CONF_DURATION)

        entities.append(Timer(hass, object_id, name, icon, duration))

    if not entities:
        return False

    component.async_register_entity_service(
        SERVICE_START, SERVICE_SCHEMA_DURATION, "async_start"
    )
    component.async_register_entity_service(
        SERVICE_PAUSE, ENTITY_SERVICE_SCHEMA, "async_pause"
    )
    component.async_register_entity_service(
        SERVICE_CANCEL, ENTITY_SERVICE_SCHEMA, "async_cancel"
    )
    component.async_register_entity_service(
        SERVICE_FINISH, ENTITY_SERVICE_SCHEMA, "async_finish"
    )

    await component.async_add_entities(entities)
    return True


class Timer(RestoreEntity):
    """Representation of a timer."""

    def __init__(self, hass, object_id, name, icon, duration):
        """Initialize a timer."""
        self.entity_id = ENTITY_ID_FORMAT.format(object_id)
        self._name = name
        self._state = STATUS_IDLE
        self._duration = duration
        self._remaining = self._duration
        self._icon = icon
        self._hass = hass
        self._end = None
        self._listener = None

    @property
    def should_poll(self):
        """If entity should be polled."""