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

export function useTelemetryStream() {
  const [message, setMessage] = useState<TelemetryBroadcastMessage | null>(null);
  const [connected, setConnected] = useState(false);

  useEffect(() => {
    const client = new Client({
      brokerURL: "ws://localhost:18450/ws",
      reconnectDelay: 3000,

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

        client.subscribe("/topic/telemetry/latest", (frame) => {
          const payload = JSON.parse(frame.body) as TelemetryBroadcastMessage;
          setMessage(payload);
        });
      },

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

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

    client.activate();

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

  return {
    connected,
    message,
    lastTimestamp: message?.timestamp ?? null,
    snapshots: message?.snapshots ?? [],
    sensorCount: message?.sensorCount ?? 0,
  };
}