"""Support for covers from FHEM"""

import voluptuous as vol
import logging

from homeassistant.components.switch import SwitchDevice, PLATFORM_SCHEMA
from homeassistant.const import CONF_NAME
import homeassistant.helpers.config_validation as cv
from . import DATA_FHEM, device_error_reporting, 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,
})


async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
    connection = hass.data[DATA_FHEM]
    switch = FhemSwitch(connection, config[CONF_NAME], config[CONF_FHEM_IDS])
    for dev_id in config[CONF_FHEM_IDS]:
        connection.register_device(dev_id, switch)
    async_add_entities([switch])


class FhemSwitch(SwitchDevice):

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

    @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 is_on(self):
        """Return true if device is on."""
        return self._on

    async def async_turn_on(self, **kwargs):
        """Turn the device on."""
        self.connection.fhem_set(self._ids[0], 'on')

    async def async_turn_off(self, **kwargs):
        """Turn the device off."""
        self.connection.fhem_set(self._ids[0], 'off')

    async def line_received(self, line):
        if line.startswith('level:'):
            _, new_state = line.split(':')
            new_state = new_state.strip().lower()
            if new_state in ('on', '100'):
                self._on = True
            if new_state in ('off', '0'):
                self._on = False
            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="Switch", component_name=self.entity_id)
