import { useEffect, useRef } from "react";
import { usePlayerName } from "../../domain/gameStore";
import { makeQuestionMarker, makeFlagMarker, makeLine } from "./markers";
import getColorGenerator from "./getColorGenerator";

const useMarkersFromGuesses = (mapRef, playersRaw, roundNum, targetPoint) => {
  // set up the flag at the target point
  useEffect(() => {
    if (targetPoint === null) {
      return;
    }
    const targetMarker = makeFlagMarker(mapRef.current, targetPoint);
    // eslint-disable-next-line consistent-return
    return () => {
      targetMarker.setMap(null);
    };
  }, [mapRef, targetPoint]);

  // get just the relevant players to put on the map
  const players = playersRaw
    ?.filter(
      ({ guesses }) => guesses[roundNum] && guesses[roundNum].score !== null
    )
    ?.map(({ name, totalScore, guesses }) => ({
      name,
      totalScore,
      guess: guesses[roundNum],
    }));

  // get the current player's name
  const playerName = usePlayerName();

  // set up the marker colors
  const playerColors = useRef({ [playerName]: "#000000" });
  const nextColor = useRef(getColorGenerator());
  if (players) {
    players
      .filter(({ name }) => !playerColors.current[name])
      .forEach(({ name }) => {
        playerColors.current[name] = nextColor.current();
      });
  }

  // draw all the player markers and trails
  useEffect(() => {
    if (!players) {
      return;
    }
    const drawings = [];
    players.forEach(({ name, totalScore, guess: { lat, lng, score } }) => {
      const color = playerColors.current[name];
      const selectedPoint = { lat, lng };

      const marker = makeQuestionMarker(
        mapRef.current,
        selectedPoint,
        `${name}\n${score} Points\n${totalScore} Total`,
        color
      );
      drawings.push(marker);

      const line = makeLine(selectedPoint, targetPoint, mapRef.current, color);
      drawings.push(line);
    });
    // eslint-disable-next-line consistent-return
    return () => drawings.forEach(drawing => drawing.setMap(null));
  }, [players, mapRef, targetPoint, playerColors]);
};

export default useMarkersFromGuesses;
