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

from devices.base import base


class powerplug(base):
    PROPERTIES = [
        "output/1",
        "output/2",
        "output/3",
        "output/4",
    ]

    def __init__(self, mqtt_client, topic):
        super().__init__(mqtt_client, topic)
        #
        for i in range(0, 4):
            self[self.PROPERTIES[i]] = False
            self.mqtt_client.add_callback(self.topic + '/output/%d/set' % (i + 1), self.__rx_set__)

    def __rx_set__(self, client, userdata, message):
        data = message.payload.decode('utf-8')
        key = message.topic.split('/')[-3] + '/' + message.topic.split('/')[-2]
        self.logger.info("Received set data for %s: %s", key, repr(data))
        self.__set__(key, data)
        self.send_device_status(key)
        if key.startswith("output/"):
            if data == "true":
                self.power_on(key)

    def send_device_status(self, key):
        data = self[key]
        self.logger.info("Sending status for %s: %s", key, repr(data))
        self.mqtt_client.send(self.topic + '/' + key, data)
