import paho.mqtt.client as mqtt
from datetime import datetime

from utils import post_energy_data


class CustomerMqtt(object):
    client = mqtt.Client(client_id='paho_pub', clean_session=True)
    client.enable_logger()

    def __init__(self):
        self.client.on_connect = self.on_connect
        self.client.on_publish = self.on_publish
        self.client.on_disconnect = self.on_disconnect
        self.client.on_message = self.on_message
        self.client.on_subscribe = self.on_subscribe

    def on_connect(self, client, obj, flags, rc):
        print("on_connect", datetime.now())
        print("connected rc: " + str(rc))
        self.client.subscribe(topic="v1/gateway/telemetry")

    def on_publish(self, client, obj, mid):
        ...

    def on_message(self, client, userdata, message):
        msg = eval(message.payload.decode())
        gate_id = msg["gateid"]
        print("on_message", datetime.now(), "gate_id:", gate_id)
        type_ = msg["type"]
        time = msg["time"]
        if type_ == "report":
            if datetime.now().minute % 5 == 0:
                post_energy_data(msg["meter"], gate_id, time)

    def on_subscribe(self, client, userdata, mid, granted_qos):
        print("on_subscribe", datetime.now())

    def on_unsubscribe(self, client, userdata, mid):
        print("on_unsubscribe", datetime.now())

    def on_disconnect(self, client, userdata, rc):
        print("on_disconnect", datetime.now())

    def on_log(self, client, userdata, level, buf):
        print("on_log", datetime.now())

    def run(self):
        self.client.connect("61.164.221.2", 1883, 60)
        # self.client.username_pw_set('', '')
        self.client.loop_forever()


if __name__ == '__main__':
    protocol = CustomerMqtt()
    protocol.run()
