
import os
import rrdtool
import paho.mqtt.client as mqtt


def on_disconnect(client, userdata, rc):
    print("Disconnected, trying to reconnect...")
    try:
        client.reconnect()
    except Exception as e:
        print(f"Reconnect failed: {e}")


def on_message(client, userdata, msg):
    mydata = msg.payload.decode("utf-8")  # decode bytes to string
    mysplitdata = mydata.split(" ")

    if mysplitdata[1].startswith("/"):
        mynewdata = mysplitdata[1][1:]
    else:
        mynewdata = mysplitdata[1]

    rrd_file = mynewdata + ".rrd"

    if not os.path.exists(rrd_file):
        if mynewdata.startswith(("1", "2")):
            rrdtool.create(
                rrd_file,
                "--start", "-3600",
                "--step", "15",
                "DS:sensor:GAUGE:60:U:U",
                "RRA:LAST:0.5:1:240",
                "RRA:LAST:0.5:1:5760",
                "RRA:LAST:0.5:1:40320",
                "RRA:LAST:0.5:4:43200",
                "RRA:LAST:0.5:4:525600",
            )
    else:
        try:
            # Example: update RRD with "<timestamp>:<value>"
            ret = rrdtool.update(rrd_file, f"{mysplitdata[0]}:{mysplitdata[2]}")
        except Exception as e:
            print(f"RRD update failed: {e}")


def on_publish(client, userdata, mid):
    pass


client = mqtt.Client(client_id="Xristos", clean_session=False)
client.on_message = on_message
client.on_publish = on_publish
client.on_disconnect = on_disconnect

client.connect("127.0.0.1")
client.subscribe("raspberry/sensors", qos=1)

# Start network loop
client.loop_forever()
