import logging

try:
    from config import APP_NAME as ROOT_LOGGER_NAME
except ImportError:
    ROOT_LOGGER_NAME = 'root'


class base(dict):
    """A base device for all devicetypes

    Args:
        mqtt_client (mqtt.mqtt_client): A MQTT Client instance
        topic (str): the base topic for this device
    """
    PROPERTIES = []

    def __init__(self, mqtt_client, topic):
        super().__init__()
        self.mqtt_client = mqtt_client
        self.topic = topic
        #
        self.logger = logging.getLogger(ROOT_LOGGER_NAME).getChild("devices")
        for entry in self.topic.split('/'):
            self.logger = self.logger.getChild(entry)
        #
        self.__power_on_inst__ = {}

    def __set__(self, key, data):
        if key in self.PROPERTIES:
            self.logger.debug("Setting new property %s to %s", key, repr(data))
            self[key] = data
        else:
            self.logger.warning("Ignoring unsupported property %s", key)

    def power_on(self, key):
        for i in self.__power_on_inst__.get(key, []):
            self.logger.info("Power on action for %s will be executed.", i.topic)
            i.power_on_action()

    def register_power_on_instance(self, inst, key):
        if key not in self.__power_on_inst__:
            self.__power_on_inst__[key] = []
        if inst not in self.__power_on_inst__[key]:
            self.__power_on_inst__[key].append(inst)

    def power_on_action(self):
        pass
