import { useEffect, useState } from "react";
import {
  useGameId,
  useCurrentRound,
  dispatch,
} from "../../../domain/gameStore";
import { getFirstSubmitter } from "../../../domain/apiMethods";

const useRaceModeCheck = (rate, cutoffTime) => {
  const [first, setFirst] = useState(null);
  const gameId = useGameId();
  const round = useCurrentRound();
  useEffect(() => {
    if (first !== null) {
      return;
    }
    const update = async () => {
      const firstRes = await getFirstSubmitter(gameId, round);
      if (firstRes !== null) {
        dispatch.updateRoundSeconds(r => Math.min(r, cutoffTime));
        setFirst(firstRes);
      }
    };
    update();
    const interval = setInterval(update, rate);
    // eslint-disable-next-line consistent-return
    return () => clearInterval(interval);
  }, [first, gameId, round, rate, cutoffTime]);
  const [faded, setFaded] = useState(false);
  // eslint-disable-next-line consistent-return
  useEffect(() => {
    if (first !== null) {
      const timeout = setTimeout(() => setFaded(true), 2000);
      return () => clearTimeout(timeout);
    }
  }, [first]);

  return [first, faded];
};

export default useRaceModeCheck;
