import { useEffect, useState } from "react";
import { dispatch, useRoundSeconds } from "../../../../domain/gameStore";

export const useMapResizeKeybindings = toggleMapSize => {
  useEffect(() => {
    const listener = event => {
      if (event.code === "Escape") {
        toggleMapSize();
      }
    };
    document.addEventListener("keydown", listener, false);
    return () => document.removeEventListener("keydown", listener, false);
  }, [toggleMapSize]);
};

export const useRoundTimer = onTimeout => {
  const remaining = useRoundSeconds();
  // eslint-disable-next-line consistent-return
  useEffect(() => {
    if (remaining > 0) {
      const timeout = setTimeout(() => {
        dispatch.updateRoundSeconds(r => r - 1);
      }, 1000);
      return () => clearTimeout(timeout);
    }
  }, [remaining]);
  const [called, setCalled] = useState(false);
  useEffect(() => {
    if (!called && remaining <= 0) {
      onTimeout();
      setCalled(true);
    }
  }, [onTimeout, remaining, called]);
  return remaining;
};
