import React, { useState, useEffect } from 'react';
import { gameInfo, getGuesses, sendGuess } from "../../../domain/GGSHService";
import Loading from '../../util/Loading';
import GuessPane from "./GuessPane";
import PositionedStreetView from "./PositionedStreetView";

const GamePanelContainer = ({ gameId, playerName, onRoundEnd, onGameEnd }) => {
  const [{ currentRound, targetPoint, roundSeconds }, setRoundInfo] = useState({currentRound: null, targetPoint: null, roundSeconds: null});
  const [submitDisabled, setSubmitDisabled] = useState(false);
  const [selectedPoint, setSelectedPoint] = useState(null);

  useEffect(() => {
    const setup = async () => {
      const { currentRound } = await getGuesses(gameId, playerName);
      if (currentRound) {
        const { coords, timer } = await gameInfo(gameId);
        const targetPoint = coords[currentRound];
        setRoundInfo({ currentRound, targetPoint, roundSeconds: timer });
      } else {
        onGameEnd();
      }
    }
    setup();
  }, [gameId, playerName, onGameEnd]);

  if (!currentRound || !targetPoint || !roundSeconds) {
    return <Loading/>
  }

  const handleSubmitGuess = async () => {
    setSubmitDisabled(true);
    const { score, totalScore } = await sendGuess(gameId, playerName, currentRound, selectedPoint || { timeout: true });
    onRoundEnd({
      roundNum: currentRound,
      selectedPoint,
      targetPoint,
      score,
      totalScore,
    });
  }

  return (
    <div className="game-panel">
      <div className="game-panel__streetview">
          <PositionedStreetView position={targetPoint} />
      </div>
      <div className="game-panel__spacer"/>
      <GuessPane
        roundSeconds={roundSeconds}
        onTimeout={handleSubmitGuess}
        onSelectPoint={setSelectedPoint}
        onSubmitGuess={handleSubmitGuess}
        submitDisabled={submitDisabled || selectedPoint === null}
      />
    </div>
  );
}

export default GamePanelContainer;
