"""
Support for HomematicIP via Accesspoint.
switch: SwitchingGroup, PlugableSwitchMeasuring, PlugableSwitch
"""

import asyncio
import logging
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.event import async_track_state_change
from homeassistant.helpers.restore_state import async_get_last_state
from homeassistant.const import STATE_UNKNOWN, STATE_ON, STATE_OFF
from custom_components.homematicip import (HomeMaticIP_GenericDevice, DOMAIN, 
    DOMAIN_GROUP_CHANGED, DOMAIN_DEVICE_CHANGED) 
from homeassistant.const import (
    STATE_OFF, STATE_ON, STATE_STANDBY, STATE_UNKNOWN, ATTR_ENTITY_ID)
from homeassistant.components.light import Light
from time import sleep

import homematicip
from homematicip import SwitchingGroup

_LOGGER = logging.getLogger(__name__)

@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Perform the setup for HomeMaticIP light devices."""
    _LOGGER.info("Setting up HomeMaticIP lght devices")
    homeid = discovery_info['homeid']
    home = hass.data[DOMAIN][homeid]   
#    for group in home.groups:
#        if group.groupType == 'SWITCHING':
#            async_add_devices([HomeMaticIP_LightGroup(hass, home, group)])    
    for device in home.devices:
        if isinstance(device, homematicip.BrandSwitchMeasuring): 
            async_add_devices([HomeMaticIP_BrandSwitchMeasuring(hass, home, device)])
    return True


class HomeMaticIP_BrandSwitchMeasuring(HomeMaticIP_GenericDevice, Light):
    """HomematicIP BrandSwitchMeasuring."""

    def __init__(self, hass, home, device):
        """Initialize the device."""
        HomeMaticIP_GenericDevice.__init__(self, hass, home, device, signal = DOMAIN_DEVICE_CHANGED)
        _LOGGER.info("Setting up the HomeMaticIP Brand Switch Measuring: {}".format(self._device.label))
    
    @property
    def is_on(self):
        """Return true if device is on."""
#        _LOGGER.info("Is on ({}): {}".format(self._device.id, self._device.on))
        return self._device.on

    @asyncio.coroutine
    def async_turn_on(self, **kwargs):
        """Turn device on."""
        self._device.turn_on()
        yield from self.schedule_update_ha_state()
#        _LOGGER.info("Turn on the device: {}".format(self._device.on))
        
    @asyncio.coroutine
    def async_turn_off(self, **kwargs):
        """Turn device off."""
        self._device.turn_off()
        yield from self.schedule_update_ha_state()
#        _LOGGER.info("Turn off the device: {}".format(self._device.on))

    @property
    def current_power_w(self):
        """Return the current power usage in W."""
        return getattr(self._device, "currentPowerConsumption", None)
        
    @property
    def today_energy_kwh(self):
        """Return the power usage in kWh."""
        return getattr(self._device, "energyCounter", None)        



class  HomeMaticIP_LightGroup(HomeMaticIP_GenericDevice, Light):
    """MomematicIP SwitchingGroup."""
    
    def __init__(self, hass, home, device):
        """Initialize the device."""
        _LOGGER.info("Setting up the HomeMaticIP Light Group")
        HomeMaticIP_GenericDevice.__init__(self, hass, home, device, signal = DOMAIN_GROUP_CHANGED)

    @property
    def is_on(self):
        """Return true if device is on."""
        _LOGGER.info("The group is s_on: {}".format(self._device.on))
        return self._device.on
        
#    @property
#    def state(self):
#        """Return true if device is on."""
#        _LOGGER.info("The group state is: {}".format(self._device.on))
#        return self._device.on
 
    @asyncio.coroutine                    
    def async_set_state(self, **kwargs):
        """Turn device on."""
        self._device.set_switch_state(True)
        yield from self.schedule_update_ha_state()
   
    @asyncio.coroutine                    
    def async_turn_on(self, **kwargs):
        """Turn device on."""
        self._device.set_switch_state(True)
        self.schedule_update_ha_state()

    @asyncio.coroutine
    def async_turn_off(self, **kwargs):
        """Turn device off."""
        self._device.set_switch_state(False)
        self.schedule_update_ha_state()
        
    
    
    
