# -*- coding: utf-8 -*-
from smarthome.Importer import get_smarthome_config
from smarthome.lib_utils.Constants import *

__author__ = 'Artem Krutalevich'

__all__ = ['get_smarthome_state', 'State']

# Make module globals a placeholder for once created object
smarthome_state = None


class State:
    """
    Global State class as a singleton.
    Stores Home and its child contexts.
    """
    __shared_state = {}

    def __init__(self, config=get_smarthome_config(), *args, **kwargs):
        if self.__class__.__shared_state.get(SHARED_STATE):
            self.sync_state()
            if not globals()[STATE_GLOBAL_NAME]:
                global smarthome_state
                smarthome_state = self
            return
        self.shared_state = True
        self.config = config
        self.state_updated = None
        self.state_consistent = None

    def sync_state(self):
        self.__dict__ = self.__class__.__shared_state

    def get_context(self, component, *args, **kwargs):
        return self

    def update_context(self, component, *args, **kwargs):
        return self

    def check_state_consistency(self):
        """
        Checks State for consistent context, performs sanity cleanups if needed.
        :return:
        """
        return self

    def is_state_consistent(self):
        return self.state_consistent

    def diag_state(self):
        return self.state_consistent

    def __str__(self):
        return ','.join((i for i in self.__dict__ if i))

    def __call__(self, *args, **kwargs):
        return self.__str__()


class Component:
    COMPONENTS_LIB = []

    def __init__(self, comp_id=0, name=COMPONENT_NAME_UNKNOWN, target=COMPONENT_TARGET_UNKNOWN):
        self.comp_id = comp_id
        self.name = name
        self.target = target
        self.__class__.__name__.COMPONENTS_LIB.append(self)

    def _get_component_id(self):
        if not len(self.__class__.__name__.COMPONENTS_LIB):
            return None
        else:
            from operator import itemgetter
            return sorted(Component.COMPONENTS_LIB, key=itemgetter('comp_id'))[-1]

    @staticmethod
    def get_component_by_id(comp_id):
        for component in Component.COMPONENTS_LIB:
            if component.id == comp_id:
                return component
            else:

                return None


def get_smarthome_state(*args, **kwargs):
    # Verify that new SmartHome Config main instance will not override already existing one
    global smarthome_state
    if not globals()[STATE_GLOBAL_NAME]:
        smarthome_state = State(*args, **kwargs)
    return globals()[STATE_GLOBAL_NAME]
