"""Support for covers from FHEM"""

import voluptuous as vol
import logging

from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_NAME
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from . import DATA_FHEM, device_error_reporting, CONF_FHEM_SENSOR_TYPE, CONF_FHEM_IDS


_LOGGER = logging.getLogger(__name__)


PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_FHEM_IDS): vol.All(cv.ensure_list, [cv.string]),
    vol.Required(CONF_NAME): cv.string,
    vol.Optional(CONF_FHEM_SENSOR_TYPE, default='brightness'): vol.In(('brightness',)),
})


async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
    connection = hass.data[DATA_FHEM]

    sensor = FhemSensor(connection,
                       config[CONF_NAME],
                       config[CONF_FHEM_IDS],
                       config[CONF_FHEM_SENSOR_TYPE])
    for dev_id in config[CONF_FHEM_IDS]:
        connection.register_device(dev_id, sensor)
    async_add_entities([sensor])


class FhemSensor(Entity):

    def __init__(self, connection, name, ids, sensor_type):
        self._on = None
        self.connection = connection
        self._ids = ids
        self._name = name
        self._type = sensor_type
        self._available = True
        self._state = None
        self._unsubscribe_motion_off = None

    @property
    def name(self):
        return self._name

    @property
    def should_poll(self):
        """No polling needed."""
        return False

    @property
    def available(self) -> bool:
        return self._available and self.connection.connected

    @property
    def state(self):
        return self._state

    async def line_received(self, line):
        if self._type == 'brightness' and line.startswith('brightness'):
            self._available = True
            _, new_value = line.split(':')
            self._state = int(float(new_value) / 255 * 100)
            await self.async_update_ha_state()
        elif line.startswith('ResndFail') or line.startswith('MISSING ACK'):
            self._available = False
            await self.async_update_ha_state()
        else:
            device_error_reporting(self.hass, line, component_type="Sensor", component_name=self.entity_id)

    @property
    def device_state_attributes(self):
        return None

    @property
    def unit_of_measurement(self):
        if self._type == 'brightness':
            return '%'
