import { useCallback, useEffect, useState } from "react";
import ReconnectingWebSocket from "reconnecting-websocket";
import { isBrowser } from "../utils/utils.js";
import useReconnecting from "./useReconnecting.jsx";

export default function useWebsocket() {
  const [ws, setWs] = useState(null);
  const [url, setUrl] = useState();

  const connect = (url) => {
    setWs(new ReconnectingWebSocket(url));
  };

  const reconnect = (id_code, clientId) => {
    if (ws == null) {
      let tmpWs = new ReconnectingWebSocket(
        `ws://192.168.1.18:8000/ws/room/${id_code}`
      );
      tmpWs.send(
        JSON.stringify({
          data: {
            type: "reconnect",
            clientId: clientId,
          },
        })
      );
      setWs(tmpWs);
      tmpWs = null;
    }
  };

  const [messageHandlers, setMessageHandlers] = useState(new Set());

  const addMessageHandler = (handler) => {
    let newSet = messageHandlers;
    newSet.add(handler);
    setMessageHandlers(newSet);
  };

  const removeMessageHandler = (handler) => {
    let newSet = messageHandlers;
    newSet.delete(handler);
    setMessageHandlers(newSet);
  };

  useEffect(() => {
    if (isBrowser && ws != null) {
      ws.onmessage = (e) => {
        console.log('Handler principal',e )
        messageHandlers.forEach((handler) => {
          handler(e);
        });
      };
    }
  }, [ws, messageHandlers]);

  return { connect, addMessageHandler, removeMessageHandler, reconnect, ws };
}
