import json
import paho.mqtt.client as mqtt
import random

class KiwisIoT:
    def __init__(self, topic="default"):
        self.topic = topic
        self.client = mqtt.Client()
        self.callback = None
        self.last_payload = None

        
        self.broker = "kiwisiot.in"
        self.port = 1883
        self.username = "Kiwisiot"
        self.password = "Kiwistron@26"

        self.client.username_pw_set(self.username, self.password)
        self.client.on_message = self._on_message
        self.client.on_disconnect = self._on_disconnect

 
    def connect(self):
        print("[KiwisIoT] Connecting to broker...")
        self.client.connect(self.broker, self.port, 60)
        self.client.subscribe(self.topic)

    def loop_start(self):
        self.client.loop_start()

 
    def _on_disconnect(self, client, userdata, rc):
        print("[MQTT] Disconnected... Reconnecting")
        while True:
            try:
                client.reconnect()
                print("[MQTT] Reconnected")
                break
            except:
                pass

   
    def send(self, channel, value):
        payload = json.dumps({channel: value})
        self.last_payload = payload
        self.client.publish(self.topic, payload)
        print("[TX]", payload)

    def send_json(self, json_data):
        self.last_payload = json_data
        self.client.publish(self.topic, json_data)
        print("[TX]", json_data)

    
    def on_receive(self, callback):
        self.callback = callback

    def _on_message(self, client, userdata, msg):
        data = msg.payload.decode()

        if data == self.last_payload:
            return

        try:
            parsed = json.loads(data)
            for k, v in parsed.items():
                print(f"[RX] CH={k} VAL={v}")
                if self.callback:
                    self.callback(k, str(v))
        except Exception as e:
            print("[ERROR]", e)
