"""This platform allows several lights to be grouped into one light."""
from collections import Counter
import itertools
import logging
from typing import Any, Callable, Iterator, List, Optional, Tuple

import voluptuous as vol

from homeassistant.components import light
from homeassistant.const import (
    ATTR_ENTITY_ID, ATTR_SUPPORTED_FEATURES, CONF_ENTITIES, CONF_NAME,
    STATE_ON, STATE_UNAVAILABLE)
from homeassistant.core import State, callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import async_track_state_change
from homeassistant.helpers.typing import ConfigType, HomeAssistantType

from homeassistant.components.light import (
    ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_EFFECT, ATTR_EFFECT_LIST,
    ATTR_FLASH, ATTR_HS_COLOR, ATTR_MAX_MIREDS, ATTR_MIN_MIREDS,
    ATTR_TRANSITION, ATTR_WHITE_VALUE, PLATFORM_SCHEMA, SUPPORT_BRIGHTNESS,
    SUPPORT_COLOR, SUPPORT_COLOR_TEMP, SUPPORT_EFFECT, SUPPORT_FLASH,
    SUPPORT_TRANSITION, SUPPORT_WHITE_VALUE)

_LOGGER = logging.getLogger(__name__)

DEFAULT_NAME = 'Light Group'

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
    vol.Required(CONF_ENTITIES): cv.entities_domain(light.DOMAIN)
})

SUPPORT_GROUP_LIGHT = (SUPPORT_BRIGHTNESS | SUPPORT_COLOR_TEMP | SUPPORT_EFFECT
                       | SUPPORT_FLASH | SUPPORT_COLOR | SUPPORT_TRANSITION
                       | SUPPORT_WHITE_VALUE)


async def async_setup_platform(hass: HomeAssistantType, config: ConfigType,
                               async_add_entities,
                               discovery_info=None) -> None:
    """Initialize light.group platform."""
    async_add_entities([LightGroup(config.get(CONF_NAME),
                                   config[CONF_ENTITIES])])


class LightGroup(light.Light):
    """Representation of a light group."""

    def __init__(self, name: str, entity_ids: List[str]) -> None:
        """Initialize a light group."""
        self._name = name  # type: str
        self._entity_ids = entity_ids  # type: List[str]
        self._is_on = False  # type: bool
        self._available = False  # type: bool
        self._brightness = None  # type: Optional[int]
        self._hs_color = None  # type: Optional[Tuple[float, float]]
        self._color_temp = None  # type: Optional[int]
        self._min_mireds = 154  # type: Optional[int]
        self._max_mireds = 500  # type: Optional[int]
        self._white_value = None  # type: Optional[int]
        self._effect_list = None  # type: Optional[List[str]]
        self._effect = None  # type: Optional[str]
        self._supported_features = 0  # type: int
        self._async_unsub_state_changed = None

    async def async_added_to_hass(self) -> None:
        """Register callbacks."""
        @callback
        def async_state_changed_listener(entity_id: str, old_state: State,
                                         new_state: State):
            """Handle child updates."""
            self.async_schedule_update_ha_state(True)

        self._async_unsub_state_changed = async_track_state_change(
            self.hass, self._entity_ids, async_state_changed_listener)