"""Support for MQTT climate devices."""
import logging

import voluptuous as vol

from homeassistant.components import climate, mqtt
from homeassistant.components.climate import (
    PLATFORM_SCHEMA as CLIMATE_PLATFORM_SCHEMA, ClimateDevice)
from homeassistant.components.climate.const import (
    ATTR_HVAC_MODE, ATTR_TARGET_TEMP_HIGH, ATTR_TARGET_TEMP_LOW,
    DEFAULT_MAX_TEMP, DEFAULT_MIN_TEMP, HVAC_MODE_AUTO, HVAC_MODE_COOL,
    HVAC_MODE_DRY, HVAC_MODE_FAN_ONLY, HVAC_MODE_HEAT, HVAC_MODE_OFF,
    SUPPORT_AUX_HEAT, SUPPORT_FAN_MODE, SUPPORT_PRESET_MODE,
    SUPPORT_SWING_MODE, SUPPORT_TARGET_TEMPERATURE, PRESET_AWAY,
    SUPPORT_TARGET_TEMPERATURE_RANGE)
from homeassistant.components.fan import SPEED_HIGH, SPEED_LOW, SPEED_MEDIUM
from homeassistant.const import (
    ATTR_TEMPERATURE, CONF_DEVICE, CONF_NAME, CONF_VALUE_TEMPLATE, STATE_ON)
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.typing import ConfigType, HomeAssistantType

from . import (
    ATTR_DISCOVERY_HASH, CONF_QOS, CONF_RETAIN, CONF_UNIQUE_ID,
    MQTT_BASE_PLATFORM_SCHEMA, MqttAttributes, MqttAvailability,
    MqttDiscoveryUpdate, MqttEntityDeviceInfo, subscription)
from .discovery import MQTT_DISCOVERY_NEW, clear_discovery_hash

_LOGGER = logging.getLogger(__name__)

DEFAULT_NAME = 'MQTT HVAC'

CONF_ACTION_TEMPLATE = 'action_template'
CONF_ACTION_TOPIC = 'action_topic'
CONF_AUX_COMMAND_TOPIC = 'aux_command_topic'
CONF_AUX_STATE_TEMPLATE = 'aux_state_template'
CONF_AUX_STATE_TOPIC = 'aux_state_topic'
CONF_AWAY_MODE_COMMAND_TOPIC = 'away_mode_command_topic'
CONF_AWAY_MODE_STATE_TEMPLATE = 'away_mode_state_template'
CONF_AWAY_MODE_STATE_TOPIC = 'away_mode_state_topic'
CONF_CURRENT_TEMP_TEMPLATE = 'current_temperature_template'
CONF_CURRENT_TEMP_TOPIC = 'current_temperature_topic'
CONF_FAN_MODE_COMMAND_TOPIC = 'fan_mode_command_topic'
CONF_FAN_MODE_LIST = 'fan_modes'
CONF_FAN_MODE_STATE_TEMPLATE = 'fan_mode_state_template'
CONF_FAN_MODE_STATE_TOPIC = 'fan_mode_state_topic'
CONF_HOLD_COMMAND_TOPIC = 'hold_command_topic'
CONF_HOLD_STATE_TEMPLATE = 'hold_state_template'
CONF_HOLD_STATE_TOPIC = 'hold_state_topic'
CONF_HOLD_LIST = 'hold_modes'
CONF_MODE_COMMAND_TOPIC = 'mode_command_topic'
CONF_MODE_LIST = 'modes'
CONF_MODE_STATE_TEMPLATE = 'mode_state_template'
CONF_MODE_STATE_TOPIC = 'mode_state_topic'
CONF_PAYLOAD_OFF = 'payload_off'
CONF_PAYLOAD_ON = 'payload_on'
CONF_POWER_COMMAND_TOPIC = 'power_command_topic'
CONF_POWER_STATE_TEMPLATE = 'power_state_template'
CONF_POWER_STATE_TOPIC = 'power_state_topic'
CONF_SEND_IF_OFF = 'send_if_off'
CONF_SWING_MODE_COMMAND_TOPIC = 'swing_mode_command_topic'
CONF_SWING_MODE_LIST = 'swing_modes'
CONF_SWING_MODE_STATE_TEMPLATE = 'swing_mode_state_template'
CONF_SWING_MODE_STATE_TOPIC = 'swing_mode_state_topic'
CONF_TEMP_COMMAND_TOPIC = 'temperature_command_topic'
CONF_TEMP_HIGH_COMMAND_TOPIC = 'temperature_high_command_topic'
CONF_TEMP_HIGH_STATE_TEMPLATE = 'temperature_high_state_template'
CONF_TEMP_HIGH_STATE_TOPIC = 'temperature_high_state_topic'
CONF_TEMP_LOW_COMMAND_TOPIC = 'temperature_low_command_topic'
CONF_TEMP_LOW_STATE_TEMPLATE = 'temperature_low_state_template'
CONF_TEMP_LOW_STATE_TOPIC = 'temperature_low_state_topic'
CONF_TEMP_STATE_TEMPLATE = 'temperature_state_template'
CONF_TEMP_STATE_TOPIC = 'temperature_state_topic'
CONF_TEMP_INITIAL = 'initial'
CONF_TEMP_MAX = 'max_temp'
CONF_TEMP_MIN = 'min_temp'
CONF_TEMP_STEP = 'temp_step'

TEMPLATE_KEYS = (
    CONF_AUX_STATE_TEMPLATE,
    CONF_AWAY_MODE_STATE_TEMPLATE,
    CONF_CURRENT_TEMP_TEMPLATE,
    CONF_FAN_MODE_STATE_TEMPLATE,
    CONF_HOLD_STATE_TEMPLATE,
    CONF_MODE_STATE_TEMPLATE,
    CONF_POWER_STATE_TEMPLATE,
    CONF_ACTION_TEMPLATE,
    CONF_SWING_MODE_STATE_TEMPLATE,
    CONF_TEMP_HIGH_STATE_TEMPLATE,
    CONF_TEMP_LOW_STATE_TEMPLATE,
    CONF_TEMP_STATE_TEMPLATE,
)

TOPIC_KEYS = (
    CONF_AUX_COMMAND_TOPIC,
    CONF_AUX_STATE_TOPIC,
    CONF_AWAY_MODE_COMMAND_TOPIC,
    CONF_AWAY_MODE_STATE_TOPIC,
    CONF_CURRENT_TEMP_TOPIC,
    CONF_FAN_MODE_COMMAND_TOPIC,
    CONF_FAN_MODE_STATE_TOPIC,
    CONF_HOLD_COMMAND_TOPIC,
    CONF_HOLD_STATE_TOPIC,
    CONF_MODE_COMMAND_TOPIC,
    CONF_MODE_STATE_TOPIC,
    CONF_POWER_COMMAND_TOPIC,
    CONF_POWER_STATE_TOPIC,
    CONF_ACTION_TOPIC,
    CONF_SWING_MODE_COMMAND_TOPIC,
    CONF_SWING_MODE_STATE_TOPIC,
    CONF_TEMP_COMMAND_TOPIC,
    CONF_TEMP_HIGH_COMMAND_TOPIC,
    CONF_TEMP_HIGH_STATE_TOPIC,
    CONF_TEMP_LOW_COMMAND_TOPIC,
    CONF_TEMP_LOW_STATE_TOPIC,
    CONF_TEMP_STATE_TOPIC,
)

SCHEMA_BASE = CLIMATE_PLATFORM_SCHEMA.extend(MQTT_BASE_PLATFORM_SCHEMA.schema)
PLATFORM_SCHEMA = SCHEMA_BASE.extend({
    vol.Optional(CONF_AUX_COMMAND_TOPIC): mqtt.valid_publish_topic,
    vol.Optional(CONF_AUX_STATE_TEMPLATE): cv.template,
    vol.Optional(CONF_AUX_STATE_TOPIC): mqtt.valid_subscribe_topic,
    vol.Optional(CONF_AWAY_MODE_COMMAND_TOPIC): mqtt.valid_publish_topic,
    vol.Optional(CONF_AWAY_MODE_STATE_TEMPLATE): cv.template,
    vol.Optional(CONF_AWAY_MODE_STATE_TOPIC): mqtt.valid_subscribe_topic,
    vol.Optional(CONF_CURRENT_TEMP_TEMPLATE): cv.template,
    vol.Optional(CONF_CURRENT_TEMP_TOPIC): mqtt.valid_subscribe_topic,
    vol.Optional(CONF_DEVICE): mqtt.MQTT_ENTITY_DEVICE_INFO_SCHEMA,
    vol.Optional(CONF_FAN_MODE_COMMAND_TOPIC): mqtt.valid_publish_topic,
    vol.Optional(CONF_FAN_MODE_LIST,
                 default=[HVAC_MODE_AUTO, SPEED_LOW,
                          SPEED_MEDIUM, SPEED_HIGH]): cv.ensure_list,
    vol.Optional(CONF_FAN_MODE_STATE_TEMPLATE): cv.template,
    vol.Optional(CONF_FAN_MODE_STATE_TOPIC): mqtt.valid_subscribe_topic,
    vol.Optional(CONF_HOLD_COMMAND_TOPIC): mqtt.valid_publish_topic,
    vol.Optional(CONF_HOLD_STATE_TEMPLATE): cv.template,
    vol.Optional(CONF_HOLD_STATE_TOPIC): mqtt.valid_subscribe_topic,
    vol.Optional(CONF_HOLD_LIST, default=list): cv.ensure_list,
    vol.Optional(CONF_MODE_COMMAND_TOPIC): mqtt.valid_publish_topic,
    vol.Optional(CONF_MODE_LIST,
                 default=[HVAC_MODE_AUTO, HVAC_MODE_OFF, HVAC_MODE_COOL,
                          HVAC_MODE_HEAT,
                          HVAC_MODE_DRY, HVAC_MODE_FAN_ONLY]): cv.ensure_list,
    vol.Optional(CONF_MODE_STATE_TEMPLATE): cv.template,
    vol.Optional(CONF_MODE_STATE_TOPIC): mqtt.valid_subscribe_topic,
    vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
    vol.Optional(CONF_PAYLOAD_ON, default="ON"): cv.string,
    vol.Optional(CONF_PAYLOAD_OFF, default="OFF"): cv.string,
    vol.Optional(CONF_POWER_COMMAND_TOPIC): mqtt.valid_publish_topic,
    vol.Optional(CONF_POWER_STATE_TEMPLATE): cv.template,
    vol.Optional(CONF_POWER_STATE_TOPIC): mqtt.valid_subscribe_topic,
    vol.Optional(CONF_RETAIN, default=mqtt.DEFAULT_RETAIN): cv.boolean,
    vol.Optional(CONF_SEND_IF_OFF, default=True): cv.boolean,
    vol.Optional(CONF_ACTION_TEMPLATE): cv.template,
    vol.Optional(CONF_ACTION_TOPIC): mqtt.valid_subscribe_topic,
    vol.Optional(CONF_SWING_MODE_COMMAND_TOPIC): mqtt.valid_publish_topic,
    vol.Optional(CONF_SWING_MODE_LIST,
                 default=[STATE_ON, HVAC_MODE_OFF]): cv.ensure_list,
    vol.Optional(CONF_SWING_MODE_STATE_TEMPLATE): cv.template,
    vol.Optional(CONF_SWING_MODE_STATE_TOPIC): mqtt.valid_subscribe_topic,
    vol.Optional(CONF_TEMP_INITIAL, default=21): cv.positive_int,
    vol.Optional(CONF_TEMP_MIN, default=DEFAULT_MIN_TEMP): vol.Coerce(float),
    vol.Optional(CONF_TEMP_MAX, default=DEFAULT_MAX_TEMP): vol.Coerce(float),
    vol.Optional(CONF_TEMP_STEP, default=1.0): vol.Coerce(float),
    vol.Optional(CONF_TEMP_COMMAND_TOPIC): mqtt.valid_publish_topic,
    vol.Optional(CONF_TEMP_HIGH_COMMAND_TOPIC): mqtt.valid_publish_topic,
    vol.Optional(CONF_TEMP_HIGH_STATE_TOPIC): mqtt.valid_subscribe_topic,
    vol.Optional(CONF_TEMP_LOW_COMMAND_TOPIC): mqtt.valid_publish_topic,
    vol.Optional(CONF_TEMP_LOW_STATE_TOPIC): mqtt.valid_subscribe_topic,
    vol.Optional(CONF_TEMP_STATE_TEMPLATE): cv.template,
    vol.Optional(CONF_TEMP_STATE_TOPIC): mqtt.valid_subscribe_topic,
    vol.Optional(CONF_UNIQUE_ID): cv.string,
    vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
}).extend(mqtt.MQTT_AVAILABILITY_SCHEMA.schema).extend(
    mqtt.MQTT_JSON_ATTRS_SCHEMA.schema)


async def async_setup_platform(hass: HomeAssistantType, config: ConfigType,
                               async_add_entities, discovery_info=None):
    """Set up MQTT climate device through configuration.yaml."""
    await _async_setup_entity(hass, config, async_add_entities)


async def async_setup_entry(hass, config_entry, async_add_entities):
    """Set up MQTT climate device dynamically through MQTT discovery."""
    async def async_discover(discovery_payload):
        """Discover and add a MQTT climate device."""
        try:
            discovery_hash = discovery_payload.pop(ATTR_DISCOVERY_HASH)
            config = PLATFORM_SCHEMA(discovery_payload)
            await _async_setup_entity(hass, config, async_add_entities,
                                      config_entry, discovery_hash)
        except Exception:
            if discovery_hash:
                clear_discovery_hash(hass, discovery_hash)
            raise

    async_dispatcher_connect(
        hass, MQTT_DISCOVERY_NEW.format(climate.DOMAIN, 'mqtt'),
        async_discover)


async def _async_setup_entity(hass, config, async_add_entities,
                              config_entry=None, discovery_hash=None):
    """Set up the MQTT climate devices."""
    async_add_entities([MqttClimate(hass, config, config_entry,
                                    discovery_hash,)])


class MqttClimate(MqttAttributes, MqttAvailability, MqttDiscoveryUpdate,
                  MqttEntityDeviceInfo, ClimateDevice):
    """Representation of an MQTT climate device."""

    def __init__(self, hass, config, config_entry, discovery_hash):
        """Initialize the climate device."""
        self._config = config
        self._unique_id = config.get(CONF_UNIQUE_ID)
        self._sub_state = None

        self.hass = hass