import os
import base64
import json
from datetime import datetime
import paho.mqtt.client as mqtt

# MQTT-Konfiguration
MQTT_BROKER = "mqtt_broker"
MQTT_PORT = 1883
MQTT_USER = "infoscreen_taa_user"
MQTT_PASSWORD = "infoscreen_taa_MQTT25!"
TOPIC_SCREENSHOTS = "infoscreen/screenshot"
SAVE_DIR = "received_screenshots"
topics = [
    ("infoscreen/screenshot", 0),
    ("infoscreen/heartbeat", 0),
    # ... weitere Topics hier
]

# Ordner für empfangene Screenshots anlegen
os.makedirs(SAVE_DIR, exist_ok=True)

# Callback, wenn eine Nachricht eintrifft
def on_message(client, userdata, msg):
    try:
        payload = json.loads(msg.payload.decode('utf-8'))
        b64_str = payload["screenshot"]
        img_data = base64.b64decode(b64_str)
        
        # Dateiname mit Zeitstempel
        ts = datetime.fromtimestamp(payload.get("timestamp", datetime.now().timestamp()))
        filename = ts.strftime("screenshot_%Y%m%d_%H%M%S.jpg")
        filepath = os.path.join(SAVE_DIR, filename)
        
        # Bild speichern
        with open(filepath, "wb") as f:
            f.write(img_data)
        print(f"Bild gespeichert: {filepath}")
    except Exception as e:
        print("Fehler beim Verarbeiten der Nachricht:", e)

# Callback bei erfolgreicher Verbindung
def on_connect(client, userdata, flags, rc, properties):
    if rc == 0:
        print("Mit MQTT-Server verbunden.")
        client.subscribe(TOPIC_SCREENSHOTS, qos=1)
    else:
        print(f"Verbindung fehlgeschlagen (Code {rc})")

if __name__ == "__main__":
    client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
    client.username_pw_set(MQTT_USER, MQTT_PASSWORD)  # <<<< AUTHENTIFIZIERUNG
    client.on_connect = on_connect
    client.on_message = on_message
    
    client.connect(MQTT_BROKER, MQTT_PORT, keepalive=60)
    client.loop_forever()
