import { useEffect, useMemo, useState, type ReactNode } from "react";
import type { InfoBarData } from "../../types/types";
import useWebSocket from "react-use-websocket";
import { ws_config } from "../../utils/ws_config";
import { WebsocketContext, type WebsocketContextValue } from "../WebsocketContext";

type WebSocketProviderProps = {
  children: ReactNode;
};

const WebSocketProvider = ({ children }: WebSocketProviderProps) => {
  const [systemData, setSystemData] = useState<InfoBarData | null>(null);

  const infoSocket = useWebSocket(ws_config.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<WebsocketContextValue>(
    () => ({
      info: {
        data: systemData,
        readyState: infoSocket.readyState,
        sendJson: infoSocket.sendJsonMessage,
      },
    }),
    [infoSocket.readyState, infoSocket.sendJsonMessage, systemData]
  );
  return <WebsocketContext.Provider value={value}>{children}</WebsocketContext.Provider>;
};

export default WebSocketProvider;
