import { useState, useEffect } from "react";
import dequal from "dequal";
import {
  getGameConfig,
  getGameCoords,
  getPlayers,
  getLinkedGame,
} from "../domain/apiMethods";
import { useGameId } from "../domain/gameStore";

const useSingleCall = apiCall => {
  const gameId = useGameId();
  const [info, setInfo] = useState(null);

  useEffect(() => {
    apiCall(gameId).then(setInfo);
  }, [gameId, apiCall]);

  return info;
};

export const useGameConfig = () => useSingleCall(getGameConfig) ?? {};

export const useGameCoords = () => useSingleCall(getGameCoords);

const useAutoRefresh = apiCall => {
  const gameId = useGameId();
  const [info, setInfo] = useState(null);

  useEffect(() => {
    // define how to fetch info
    const fetchInfo = async () => {
      const newInfo = await apiCall(gameId);
      // TODO make equality an argument? to avoid doing dequal on deep structures?
      if (!dequal(info, newInfo)) {
        setInfo(newInfo);
      }
    };
    // when the hook triggers, fetch the game info
    fetchInfo();
    // and do it again every 5 seconds after
    const interval = setInterval(() => fetchInfo(), 5000);
    // and return a clean-up callback
    return () => {
      clearInterval(interval);
    };
  }, [gameId, apiCall, info]);

  return info;
};

export const usePlayers = () => useAutoRefresh(getPlayers);

export const useLinkedGame = () => useAutoRefresh(getLinkedGame);
