import influxdb_client
from influxdb_client.client.write_api import SYNCHRONOUS

from random import random
import time

from paho.mqtt import client as mqtt_client

import json

### MQTT ###
broker = '127.0.0.1'
port = 1883
topic = "zigbee2mqtt/bridge/logging"
client_id = f'python-mqtt-310'

### InfluxDB ###
bucket = "BUCKET"
org = "ORGANIZATION"
token = "TOKEN"
# Store the URL of your InfluxDB instance
url="127.0.0.1:8086"

client = influxdb_client.InfluxDBClient(
   url=url,
   token=token,
   org=org
)

write_api = client.write_api(write_options=SYNCHRONOUS)

### FUNCTIONS ###
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.on_connect = on_connect
    client.connect(broker, port)
    return client

def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        message = json.loads(msg.payload.decode())
        if message["level"] == "debug" and len(message["message"].split(', ')) == 4:
            #print(f"{message}")
            device = message['message'].split(', ')[0].split("'")[1]
            if device != "Coordinator":
                cluster = message['message'].split(', ')[2].split("'")[1]
                value = message['message'].split(', ')[3].split(":")[1].split("}")[0]
            
                print(f"Device {device} - cluster {cluster} = {value}")
                if cluster == "msTemperatureMeasurement":
                    val = int(value)/100
                    p = influxdb_client.Point("my_measurement").tag("device", device).field("temperature", val)
                    write_api.write(bucket=bucket, org=org, record=p)
                elif cluster == "msRelativeHumidity":
                    val = int(value)/100
                    p = influxdb_client.Point("my_measurement").tag("device", device).field("humidity", val)
                    write_api.write(bucket=bucket, org=org, record=p)
                elif cluster == "msPressureMeasurement":
                    val = int(value)/10
                    p = influxdb_client.Point("my_measurement").tag("device", device).field("pressure", val)
                    write_api.write(bucket=bucket, org=org, record=p)
                elif cluster == "msIlluminanceMeasurement":
                    val = int(value)/100
                    p = influxdb_client.Point("my_measurement").tag("device", device).field("illuminance", val)
                    write_api.write(bucket=bucket, org=org, record=p)
                elif cluster == "msCO2":
                    val = int(value)
                    p = influxdb_client.Point("my_measurement").tag("device", device).field("co2", val)
                    write_api.write(bucket=bucket, org=org, record=p)
                elif cluster == "pm25Measurement":
                    val = int(value)/10000
                    p = influxdb_client.Point("my_measurement").tag("device", device).field("dust", val)
                    write_api.write(bucket=bucket, org=org, record=p)

    client.subscribe(topic)
    client.on_message = on_message


def run():
    client = connect_mqtt()
    subscribe(client)
    client.loop_forever()


if __name__ == '__main__':
    run()
