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

import logging
import inspect

try:
    from config import APP_NAME as ROOT_LOGGER_NAME
except ImportError:
    ROOT_LOGGER_NAME = 'root'
logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__)


class room(object):
    ADD_TO_VIDEV_ALL_OFF = None

    def __init__(self, mqtt_client):
        self.mqtt_client = mqtt_client

    def all_off(self, device=None, key=None, data=None):
        logger.info("Switching all off \"%s\"", type(self).__name__)
        for name, obj in inspect.getmembers(self):
            try:
                if obj.__module__.startswith('smart_devices'):
                    obj.all_off()
            except AttributeError:
                pass    # not a module or has no method all_off

    def summer_mode(self, enable):
        for name, obj in inspect.getmembers(self):
            if obj.__class__.__name__ == 'heating_function':
                if obj.__module__ == 'function.modules':
                    obj.set(obj.KEY_SUMMER_MODE, enable)


class room_collection(object):
    ADD_TO_VIDEV_ALL_OFF = None

    def __init__(self, mqtt_client):
        self.mqtt_client = mqtt_client

    def all_off(self, device=None, key=None, data=None):
        logger.info("Switching all off \"%s\"", type(self).__name__)
        for sub_name in dir(self):
            # attribute name is not private
            if not sub_name.startswith("__"):
                sub = getattr(self, sub_name)
                # try to call all_off
                try:
                    sub.all_off()
                except AttributeError:
                    pass    # don't mind, if sub has no method all_off
                except:
                    logger.error("Failed to switch off %s (%s)", repr(sub_name), type(sub).__name__)

    def summer_mode(self, device=None, key=None, data=None):
        logger.info("Changing to %s \"%s\"", "summer mode" if data else "winter_mode", type(self).__name__)
        for sub_name in dir(self):
            # attribute name is not private
            if not sub_name.startswith("__"):
                sub = getattr(self, sub_name)
                if isinstance(sub, (room, room_collection)):
                    sub.summer_mode(data)

    def all_devices(self, object_to_analyse=None, depth=0):
        target = object_to_analyse or self
        #
        devices = []
        for name, obj in inspect.getmembers(target):
            if not callable(obj):                                       # sort out methods
                try:
                    if obj.__module__.startswith('function.') and not obj.__module__.endswith('.videv'):
                        devices.extend(self.all_devices(obj, depth+1))           # rekurse in function instances
                    elif obj.__module__ == "devices":
                        devices.append(obj)
                except AttributeError:
                    pass                                                # sort out non modules
        return devices
