import { useEffect, useState } from "react";
import { Client } from "@stomp/stompjs";
import type { MeteoModuleResponse } from "../../../types/meteo";

const WS_URL = "ws://localhost:18450/ws";
const TOPIC = "/topic/modules/meteo/latest";

export function useMeteoModuleStream() {
    const [module, setModule] = useState<MeteoModuleResponse | null>(null);
    const [connected, setConnected] = useState(false);
    const [lastTimestamp, setLastTimestamp] = useState<string | null>(null);

    useEffect(() => {
        const client = new Client({
            brokerURL: WS_URL,
            reconnectDelay: 3000,

            onConnect: () => {
                setConnected(true);

                client.subscribe(TOPIC, (message) => {
                    const payload = JSON.parse(message.body) as MeteoModuleResponse;

                    setModule(payload);
                    setLastTimestamp(payload.timestamp);
                });
            },

            onWebSocketClose: () => {
                setConnected(false);
            },

            onStompError: (frame) => {
                console.error("Meteo module STOMP error", frame);
                setConnected(false);
            },
        });

        client.activate();

        return () => {
            client.deactivate();
        };
    }, []);

    return {
        module,
        sensors: module?.sensors ?? [],
        sensorCount: module?.sensorCount ?? 0,
        connected,
        lastTimestamp,
    };
}