import React, { useState } from "react";
import {
  PRE_GAME,
  PRE_ROUND,
  IN_ROUND,
  POST_ROUND,
  POST_GAME,
  ERROR,
} from "./game-state.enum";
import HeaderAndFooter from "../util/header-and-footer.component";
import PreGame from '../screens/pre-game.component';
import PreRound from '../screens/pre-round.component';
import GamePanelContainer from "../screens/game-panel.component";
import RoundSummary from '../screens/round-summary.component';
import PlayerScoresContainer from "../screens/player-scores.component";

const initialState = {
  gameState: PRE_GAME,
  gameId: null,
  playerName: null,
  lastRound: null,
}

const Game = () => {
  const [ state, rawSetState ] = useState(initialState);
  const setGameState = gameState => rawSetState({ ...state, gameState });
  const setGameStateAnd = (gameState, updates) => rawSetState({ ...state, gameState, ...updates });

  switch (state.gameState) {
    case PRE_GAME:
      return (
        <HeaderAndFooter>
          <PreGame
            initPlayerName={state.playerName}
            onGameJoined={({ gameId, playerName }) => setGameStateAnd(PRE_ROUND, { gameId, playerName })}
          />
        </HeaderAndFooter>
      );
    case PRE_ROUND:
      return <PreRound
        gameId={state.gameId}
        playerName={state.playerName}
        onStart={() => setGameState(IN_ROUND)}
      />
    case IN_ROUND:
      return <GamePanelContainer
        gameId={state.gameId}
        playerName={state.playerName}
        onRoundEnd={lastRound => setGameStateAnd(POST_ROUND, { lastRound })}
        onGameEnd={() => setGameState(POST_GAME)}
      />
    case POST_ROUND:
      return <RoundSummary
        round={state.lastRound}
        onNext={() => setGameState(IN_ROUND)}
      />
    case POST_GAME:
      return (
        <HeaderAndFooter>
          <PlayerScoresContainer
            gameId={state.gameId}
            onReturnToStart={() => setGameState(PRE_GAME)}
          />
        </HeaderAndFooter>
      );
    case ERROR:
      // TODO - would be nice to hook this into the sub-components, maybe with a HOC?
      return <p>Application encountered unrecoverable error, please refresh the page.</p>
    default:
      setGameState(ERROR);
      return <p>Application state is inconsistent, please refresh and rejoin your previous game.</p>
  }
}

export default Game;
