import json
import time

import redis
from paho.mqtt import client as mqtt_client

r = redis.Redis(
    host='192.168.0.220',
    port=6379,
    db=111)

broker = '192.168.0.220'
port = 1883
topic = ["doc-1", "doc-2", "doc-3"]
# generate client ID with pub prefix randomly
client_id = f'["doc-1","doc-2","doc-3"]'
username = 'Mad'
password = 'public'


def connect_mqtt() -> mqtt_client:
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)

    client = mqtt_client.Client(client_id)
    client.username_pw_set(username, password)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client


def publish(client: object) -> object:
    msg_count = 0
    while True:
        time.sleep(1)
        counter = 0
        num = 1
        patients = {}
        while True:
            msg = {"patient_id": num}
            result = client.publish(topic[int((counter) % len(topic))], str(msg))
            print(result)
            status = result[0]
            if status == 0:
                print(f"Send `{str(msg)}` to topic `{topic[int((counter) % len(topic))]}`")
                if topic[int(counter % len(topic))] not in patients.keys():
                    patients[topic[int(counter % len(topic))]] = []
                    patients[topic[int(counter % len(topic))]].append(str(msg['patient_id']))
                else:
                    if str(msg['patient_id']) not in patients[topic[int(counter % len(topic))]]:
                        patients[topic[int(counter % len(topic))]].append(str(msg['patient_id']))
            else:
                print(f"Failed to send message to topic {topic}")
            # counter = counter + 1
            # num = num + 1
            if num == 5:
                # num=1
                if str(msg['patient_id']) in patients[topic[int(counter % len(topic))]]:
                    return patients
            else:
                num = num + 1
            counter = counter + 1
            print(patients)
            time.sleep(0)
            # patient_id= patient_id+1
            # time.sleep(5)
            # print(counter)

            # msg_count += 1


# def run():
#     client = connect_mqtt()
#     client.loop_start()
#     publish(client)


def run():
    client = connect_mqtt()
    client.loop_start()
    data = publish(client)
    # print(data)
    # redis_conn()
    return data


def redis_conn():
    data = run()
    # print(data)
    print(data)
    if data:
        r.set("token_details", json.dumps(data))
        return "data inserted"


# data = run()
redis_conn()
