import { useEffect, useState, useRef } from "react";
import {
  useGameId,
  useCurrentRound,
  dispatch,
} from "../../../domain/gameStore";
import { getFirstSubmitter } from "../../../domain/apiMethods";
import {
  savePanoPositionToLocalStorage,
  savePanoPovToLocalStorage,
} from "../../../domain/localStorageMethods";
/* global google */

export const useFirstSubmitter = (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]);
  return first;
};

export const useIsFaded = first => {
  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 faded;
};

export const useIsFinished = () => {
  const finished = useCurrentRound() === null;
  useEffect(() => {
    if (finished) {
      dispatch.goToSummary();
    }
  }, [finished]);
  return finished;
};

export const usePano = (panoDivRef, { lat, lng }, { heading, pitch }) => {
  const panoRef = useRef(null);
  useEffect(() => {
    const position = { lat, lng };
    const pov = { heading, pitch };
    if (panoRef.current) {
      panoRef.current.setPosition(position);
      panoRef.current.setPov(pov);
      return;
    }

    panoRef.current = new google.maps.StreetViewPanorama(panoDivRef.current, {
      position,
      pov,
      fullscreenControl: false,
      addressControl: false,
      showRoadLabels: false,
      clickToGo: true,
      visible: true,
      motionTracking: false,
      motionTrackingControl: false,
    });
  }, [panoDivRef, lat, lng, heading, pitch]);

  return panoRef;
};

export const useSavePanoSettings = panoRef => {
  useEffect(() => {
    if (panoRef.current) {
      panoRef.current.addListener("position_changed", () => {
        const { lat, lng } = panoRef.current.getPosition();
        savePanoPositionToLocalStorage(lat(), lng());
      });
      panoRef.current.addListener("pov_changed", () => {
        const { heading, pitch } = panoRef.current.getPov();
        savePanoPovToLocalStorage(heading, pitch);
      });
    }
  }, [panoRef]);
};
