import { useEffect, useMemo, useState, type ReactNode } from "react";
import { WebsocketContext, type WebSocketConextValue } from "../context/WebSocketContext";
import useWebSocket from "react-use-websocket";
import { wsConfig } from "../config/wsconfig";
import type { InfoBarData } from "../../types/types";

type WebSocketProviderProps = {
  children: ReactNode;
};

export const WebSocketProvider = ({ children }: WebSocketProviderProps) => {
  const [systemData, setSystemData] = useState<InfoBarData | null>(null);
  const infoSocket = useWebSocket(wsConfig.infoBar, { share: true, shouldReconnect: () => true });

  useEffect(() => {
    async function parseData() {
      if (infoSocket.lastMessage) {
        const text = await infoSocket.lastMessage.data.text();
        const data = JSON.parse(text);
        setSystemData(data);
      }
    }
    parseData();
  }, [infoSocket.lastMessage]);

  const value = useMemo<WebSocketConextValue>(
    () => ({
      info: {
        data: systemData,
        readyState: infoSocket.readyState,
        sendJson: infoSocket.sendJsonMessage,
      },
    }),
    [infoSocket.readyState, infoSocket.sendJsonMessage, systemData],
  );

  return <WebsocketContext.Provider value={value}>{children}</WebsocketContext.Provider>;
};
