import React, { useState, useContext, useEffect, useRef } from "react";
import { GlobalContext } from "./GlobalContext";
import "./PingPong.css";

const PingPong: React.FC = () => {
  const [count, setCount] = useState<number>(0);
  const global = useContext(GlobalContext);

  const onWsMessage = (event: MessageEvent) => {
    const data = JSON.parse(event.data as string);
    switch (data.type) {
      case "ping":
        if (global.ws) {
          global.ws.send(JSON.stringify({ type: "pong", timestamp: data.ping }));
        }
        setCount(count + 1);
        break;
      default:
        break;
    }
  };
  const refWsMessage = useRef(onWsMessage);

  useEffect(() => {
    refWsMessage.current = onWsMessage;
  });

  useEffect(() => {
    if (!global.ws) {
      return;
    }
    const cbMessage = (e: MessageEvent) => refWsMessage.current(e);
    global.ws.addEventListener("message", cbMessage);
    return () => {
      global.ws.removeEventListener("message", cbMessage);
    };
  }, [global.ws, refWsMessage]);

  return (
    <div className="PingPong">
      Game {global.gameId}: {global.name} {global.ws ? "has socket" : "no socket"} {count} pings
    </div>
  );
};

export { PingPong };
