"""
Support for ZhongHong HVAC Controller.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/climate.zhong_hong/
"""
import logging

import voluptuous as vol

from homeassistant.components.climate import (
    ATTR_OPERATION_MODE, PLATFORM_SCHEMA, STATE_COOL, STATE_DRY,
    STATE_FAN_ONLY, STATE_HEAT, SUPPORT_FAN_MODE, SUPPORT_ON_OFF,
    SUPPORT_OPERATION_MODE, SUPPORT_TARGET_TEMPERATURE, ClimateDevice)
from homeassistant.const import (ATTR_TEMPERATURE, CONF_HOST, CONF_PORT,
                                 EVENT_HOMEASSISTANT_STOP, TEMP_CELSIUS)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.dispatcher import (async_dispatcher_connect,
                                              async_dispatcher_send)

_LOGGER = logging.getLogger(__name__)

CONF_GATEWAY_ADDRRESS = 'gateway_address'

REQUIREMENTS = ['zhong_hong_hvac==1.0.9']
SIGNAL_DEVICE_ADDED = 'zhong_hong_device_added'
SIGNAL_ZHONG_HONG_HUB_START = 'zhong_hong_hub_start'

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_HOST):
    cv.string,
    vol.Optional(CONF_PORT, default=9999):
    vol.Coerce(int),
    vol.Optional(CONF_GATEWAY_ADDRRESS, default=1):
    vol.Coerce(int),
})


def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the ZhongHong HVAC platform."""
    from zhong_hong_hvac.hub import ZhongHongGateway
    host = config.get(CONF_HOST)
    port = config.get(CONF_PORT)
    gw_addr = config.get(CONF_GATEWAY_ADDRRESS)
    hub = ZhongHongGateway(host, port, gw_addr)
    devices = [
        ZhongHongClimate(hub, addr_out, addr_in)
        for (addr_out, addr_in) in hub.discovery_ac()
    ]

    _LOGGER.debug("We got %s zhong_hong climate devices", len(devices))

    hub_is_initialized = False

    async def startup():
        """Start hub socket after all climate entity is setted up."""
        nonlocal hub_is_initialized
        if not all([device.is_initialized for device in devices]):
            return

        if hub_is_initialized:
            return

        _LOGGER.debug("zhong_hong hub start listen event")
        await hass.async_add_job(hub.start_listen)
        await hass.async_add_job(hub.query_all_status)
        hub_is_initialized = True

    async_dispatcher_connect(hass, SIGNAL_DEVICE_ADDED, startup)

    # add devices after SIGNAL_DEVICE_SETTED_UP event is listend
    add_entities(devices)

    def stop_listen(event):
        """Stop ZhongHongHub socket."""
        hub.stop_listen()

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_listen)


class ZhongHongClimate(ClimateDevice):
    """Representation of a ZhongHong controller support HVAC."""

    def __init__(self, hub, addr_out, addr_in):
        """Set up the ZhongHong climate devices."""
        from zhong_hong_hvac.hvac import HVAC
        self._device = HVAC(hub, addr_out, addr_in)
        self._hub = hub
        self._current_operation = None
        self._current_temperature = None
        self._target_temperature = None
        self._current_fan_mode = None
        self._is_on = None
        self.is_initialized = False

    async def async_added_to_hass(self):