"""Support for Denon AVR receivers using their HTTP interface."""

from collections import namedtuple
import logging

import voluptuous as vol

from homeassistant.components.media_player import (
    MediaPlayerDevice, PLATFORM_SCHEMA)
from homeassistant.components.media_player.const import (
    MEDIA_TYPE_CHANNEL, MEDIA_TYPE_MUSIC, SUPPORT_NEXT_TRACK,
    SUPPORT_PAUSE, SUPPORT_PLAY, SUPPORT_PLAY_MEDIA, SUPPORT_PREVIOUS_TRACK,
    SUPPORT_SELECT_SOUND_MODE, SUPPORT_SELECT_SOURCE, SUPPORT_TURN_OFF,
    SUPPORT_TURN_ON, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET,
    SUPPORT_VOLUME_STEP)
from homeassistant.const import (
    CONF_HOST, CONF_NAME, CONF_TIMEOUT, CONF_ZONE, STATE_OFF, STATE_ON,
    STATE_PAUSED, STATE_PLAYING)
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)

ATTR_SOUND_MODE_RAW = 'sound_mode_raw'

CONF_INVALID_ZONES_ERR = 'Invalid Zone (expected Zone2 or Zone3)'
CONF_SHOW_ALL_SOURCES = 'show_all_sources'
CONF_VALID_ZONES = ['Zone2', 'Zone3']
CONF_ZONES = 'zones'

DEFAULT_SHOW_SOURCES = False
DEFAULT_TIMEOUT = 2

KEY_DENON_CACHE = 'denonavr_hosts'

SUPPORT_DENON = SUPPORT_VOLUME_STEP | SUPPORT_VOLUME_MUTE | \
    SUPPORT_TURN_ON | SUPPORT_TURN_OFF | \
    SUPPORT_SELECT_SOURCE | SUPPORT_VOLUME_SET

SUPPORT_MEDIA_MODES = SUPPORT_PLAY_MEDIA | \
    SUPPORT_PAUSE | SUPPORT_PREVIOUS_TRACK | \
    SUPPORT_NEXT_TRACK | SUPPORT_VOLUME_SET | SUPPORT_PLAY

DENON_ZONE_SCHEMA = vol.Schema({
    vol.Required(CONF_ZONE): vol.In(CONF_VALID_ZONES, CONF_INVALID_ZONES_ERR),
    vol.Optional(CONF_NAME): cv.string,
})

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Optional(CONF_HOST): cv.string,
    vol.Optional(CONF_NAME): cv.string,
    vol.Optional(CONF_SHOW_ALL_SOURCES, default=DEFAULT_SHOW_SOURCES):
        cv.boolean,
    vol.Optional(CONF_ZONES):
        vol.All(cv.ensure_list, [DENON_ZONE_SCHEMA]),
    vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int,
})

NewHost = namedtuple('NewHost', ['host', 'name'])


def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Denon platform."""
    import denonavr

    # Initialize list with receivers to be started
    receivers = []

    cache = hass.data.get(KEY_DENON_CACHE)
    if cache is None:
        cache = hass.data[KEY_DENON_CACHE] = set()

    # Get config option for show_all_sources and timeout
    show_all_sources = config.get(CONF_SHOW_ALL_SOURCES)
    timeout = config.get(CONF_TIMEOUT)

    # Get config option for additional zones
    zones = config.get(CONF_ZONES)
    if zones is not None:
        add_zones = {}
        for entry in zones:
            add_zones[entry[CONF_ZONE]] = entry.get(CONF_NAME)
    else:
        add_zones = None

    # Start assignment of host and name
    new_hosts = []
    # 1. option: manual setting
    if config.get(CONF_HOST) is not None:
        host = config.get(CONF_HOST)
        name = config.get(CONF_NAME)
        new_hosts.append(NewHost(host=host, name=name))