import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { useWebsocketContext } from "../../context/websocket.context.js";
import { checkRoom } from "../../requests/requests.room.js";
import { isBrowser } from "../../utils/utils.js";
import Layout from "../Layout.js";

export default function WaitingRoom() {
  const router = useRouter();
  const {
    isConnected,
    send,
    connect,
    addMessageHandler,
    removeMessageHandler,
    disconnect,
  } = useWebsocketContext();


  useEffect(() => {
    if (isBrowser && (sessionStorage.getItem('waiter') == null || sessionStorage.getItem('waiter_nick') == null)) {
      router.push({ pathname: `/room/join${router.query.mode[1]}` });
    }
    if (isConnected == false && isBrowser) {
      checkRoom(router.query.mode[1])
        .then(() => {
          console.log('CONNECT HERE TO')
          connect(`ws/room/${router.query.mode[1]}`);
          send({
            data: {
              type: "login",
              nick: sessionStorage.getItem("waiter_nick"),
            },
          });
        })
        .catch(() => {
          router.push({ pathname: "/room/join" });
        });
     
    }
  }, [isConnected]);

  useEffect(() => {
    let handler = (e) => {
      let data = JSON.parse(e.data);
      let type = data.type;
      switch (type) {
        case "refused":
          sessionStorage.clear();
          {
            router.push({ pathname: "/room/join" });
          }

        default:
          return;
      }
    };
    addMessageHandler(handler);
    return () => {
      removeMessageHandler(handler);
    };
  }, []);

  useEffect(() => {
    return () => {
      disconnect();
    };
  }, []); 

  return (
    <Layout page="En attente...">
      <p>Waiting Room</p>
    </Layout>
  );
}
