#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
import logging

from smart_devices.shelly import shelly as shelly_sw1
from smart_devices.shelly import shelly_rpc as shelly_pro3
from smart_devices.hue import hue_light as hue_sw_br_ct
from smart_devices.tradfri import tradfri_light as tradfri_sw
from smart_devices.tradfri import tradfri_light as tradfri_sw_br
from smart_devices.tradfri import tradfri_light as tradfri_sw_br_ct
from smart_devices.tradfri import tradfri_button as tradfri_button
from smart_devices.tradfri import tradfri_light as livarno_sw_br_ct
from smart_devices.brennenstuhl import brennenstuhl_heatingvalve
from smart_devices.silvercrest import silvercrest_button
from smart_devices.silvercrest import silvercrest_powerplug
from smart_devices.silvercrest import silvercrest_motion_sensor
from smart_devices.mydevices import powerplug as my_powerplug
from smart_devices.mydevices import audio_status
from smart_devices.mydevices import remote

from smart_devices.videv import videv_switching as videv_sw
from smart_devices.videv import videv_switch_brightness as videv_sw_br
from smart_devices.videv import videv_switch_brightness_color_temp as videv_sw_br_ct
from smart_devices.videv import videv_switching_timer as videv_sw_tm
from smart_devices.videv import videv_switching_motion as videv_sw_mo
from smart_devices.videv import videv_heating as videv_hea
from smart_devices.videv import videv_pure_switch
from smart_devices.videv import videv_multistate
from smart_devices.videv import videv_audio_player
from smart_devices.videv import videv_all_off
try:
    from config import APP_NAME as ROOT_LOGGER_NAME
except ImportError:
    ROOT_LOGGER_NAME = 'root'
logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__)


def my_ambient(mqtt_client, topic):
    logger.warning("Device type my_ambient is not yet implemented. Topic %s will not be supported", topic)
    return None


class group(object):
    def __init__(self, *args):
        super().__init__()
        self._members = args
        self._iter_counter = 0
        #
        self.methods = []
        self.variables = []
        for name in [m for m in args[0].__class__.__dict__.keys()]:
            if not name.startswith('_') and callable(getattr(args[0], name)):   # add all public callable attributes to the list
                self.methods.append(name)
            if not name.startswith('_') and not callable(getattr(args[0], name)):   # add all public callable attributes to the list
                self.variables.append(name)
        #
        for member in self:
            methods = [m for m in member.__class__.__dict__.keys() if not m.startswith(
                '_') if not m.startswith('_') and callable(getattr(args[0], m))]
            if self.methods != methods:
                raise ValueError("All given instances needs to have same methods:", self.methods, methods)
            #
            variables = [v for v in member.__class__.__dict__.keys() if not v.startswith(
                '_') if not v.startswith('_') and not callable(getattr(args[0], v))]
            if self.variables != variables:
                raise ValueError("All given instances needs to have same variables:", self.variables, variables)

    def __iter__(self):
        return self

    def __next__(self):
        if self._iter_counter < len(self):
            self._iter_counter += 1
            return self._members[self._iter_counter - 1]
        self._iter_counter = 0
        raise StopIteration

    def __getitem__(self, i):
        return self._members[i]

    def __len__(self):
        return len(self._members)

    def __getattribute__(self, name):
        def group_execution(*args, **kwargs):
            for member in self[:]:
                m = getattr(member, name)
                m(*args, **kwargs)
        try:
            rv = super().__getattribute__(name)
        except AttributeError:
            if callable(getattr(self[0], name)):
                return group_execution
            else:
                return getattr(self[0], name)
        else:
            return rv
