"""Support for control of ElkM1 sensors."""
from homeassistant.components.elkm1 import (
    DOMAIN as ELK_DOMAIN, create_elk_entities, ElkEntity)

DEPENDENCIES = [ELK_DOMAIN]


async def async_setup_platform(
        hass, config, async_add_entities, discovery_info=None):
    """Create the Elk-M1 sensor platform."""
    if discovery_info is None:
        return

    elk = hass.data[ELK_DOMAIN]['elk']
    entities = create_elk_entities(
        hass, elk.counters, 'counter', ElkCounter, [])
    entities = create_elk_entities(
        hass, elk.keypads, 'keypad', ElkKeypad, entities)
    entities = create_elk_entities(
        hass, [elk.panel], 'panel', ElkPanel, entities)
    entities = create_elk_entities(
        hass, elk.settings, 'setting', ElkSetting, entities)
    entities = create_elk_entities(
        hass, elk.zones, 'zone', ElkZone, entities)
    async_add_entities(entities, True)


def temperature_to_state(temperature, undefined_temperature):
    """Convert temperature to a state."""
    return temperature if temperature > undefined_temperature else None


class ElkSensor(ElkEntity):
    """Base representation of Elk-M1 sensor."""

    def __init__(self, element, elk, elk_data):
        """Initialize the base of all Elk sensors."""
        super().__init__(element, elk, elk_data)
        self._state = None

    @property
    def state(self):
        """Return the state of the sensor."""
        return self._state


class ElkCounter(ElkSensor):
    """Representation of an Elk-M1 Counter."""

    @property
    def icon(self):
        """Icon to use in the frontend."""
        return 'mdi:numeric'

    def _element_changed(self, element, changeset):
        self._state = self._element.value


class ElkKeypad(ElkSensor):
    """Representation of an Elk-M1 Keypad."""

    @property
    def temperature_unit(self):
        """Return the temperature unit."""
        return self._temperature_unit

    @property
    def unit_of_measurement(self):
        """Return the unit of measurement."""
        return self._temperature_unit

    @property
    def icon(self):
        """Icon to use in the frontend."""
        return 'mdi:thermometer-lines'

    @property
    def device_state_attributes(self):
        """Attributes of the sensor."""
        from elkm1_lib.util import username

        attrs = self.initial_attrs()
        attrs['area'] = self._element.area + 1
        attrs['temperature'] = self._element.temperature
        attrs['last_user_time'] = self._element.last_user_time.isoformat()