import * as React from "react";
import { FunctionComponent, useEffect, useState } from "react";
import BoardView from "./components/board/BoardView";
import { context } from "./context";
import { RTMTWS } from "./rtmt/rtmt_websocket";
import {
  channel_game_move,
  channel_leave_game,
  channel_on_game_crashed,
  channel_on_game_start,
  channel_on_game_update,
  channel_on_game_user_leave,
} from "./channel_names";
import InfoPanel from "./components/InfoPanel";
import { CommonMancalaGame, MancalaGame, Pit } from "mancala.js";
import { GameMove } from "./models/GameMove";
import PitAnimator from "./animation/PitAnimator";
import BoardViewModel from "./viewmodel/BoardViewModel";
import { v4 } from "uuid";
import { getColorByBrightness } from "./util/ColorUtil";
import { Theme } from "./theme/Theme";
import HeaderBar from "./components/HeaderBar";
import FloatingPanel from "./components/FloatingPanel";
import PageContainer from "./components/PageContainer";

type ConnectionState = "connecting" | "error" | "connected" | "reconnecting";

const Home: FunctionComponent<{ initial?: number }> = ({ initial = 0 }) => {
  const [userKey, setUserKey] = useState<string | undefined>(undefined);

  const [connectionState, setConnetionState] =
    useState<ConnectionState>("connecting");

  const [searchingOpponent, setSearchingOpponent] = useState<boolean>(false);

  const [game, setGame] = useState<CommonMancalaGame | undefined>(undefined);

  const [crashMessage, setCrashMessage] = useState<string | undefined>(undefined);

  const [userKeyWhoLeave, setUserKeyWhoLeave] = useState<string | undefined>(undefined);

  const [boardViewModel, setBoardViewModel] = useState<BoardViewModel | undefined>(undefined);

  const [boardId, setBoardId] = useState<string>("-1");

  const [pitAnimator, setPitAnimator] = useState<PitAnimator | undefined>(undefined);

  const [theme, setTheme] = useState<Theme | undefined>(undefined);

  const onConnectionDone = () => {
    setConnetionState("connected");
  };

  const onConnectionLost = () => {
    connectToServer("reconnecting");
  };

  const onConnectionError = (event: Event) => {
    setConnetionState("error");
  };

  const connectToServer = (connectionState: ConnectionState) => {
    setConnetionState(connectionState);
    context.userKeyStore.getUserKey((userKey: string) => {
      setUserKey(userKey);
      const rtmtws = context.rtmt as RTMTWS;
      if (rtmtws) {
        rtmtws.initWebSocket(
          userKey,
          onConnectionDone,
          onConnectionLost,
          onConnectionError
        );
      } else {
        console.error("context.rtmt is not RTMTWS");
      }
    });
  };

  const listenMessages = (pitAnimator: PitAnimator) => {
    context.rtmt.listenMessage(channel_on_game_start, (message: Object) => {
      const newGame: CommonMancalaGame = message as CommonMancalaGame;
      const mancalaGame = MancalaGame.createFromMancalaGame(newGame);
      setSearchingOpponent(false);
      setGame(mancalaGame);
      pitAnimator.setNewGame(mancalaGame);
    });

    context.rtmt.listenMessage(channel_on_game_update, (message: Object) => {
      const newGame: CommonMancalaGame = message as CommonMancalaGame;
      const mancalaGame = MancalaGame.createFromMancalaGame(newGame);
      setGame(mancalaGame);
      pitAnimator.setUpdatedGame(mancalaGame);
    });

    context.rtmt.listenMessage(channel_on_game_crashed, (message: any) => {
      const newCrashMessage = message as string;
      console.error("on_game_crash");
      console.error(newCrashMessage);
      setCrashMessage(newCrashMessage);
    });

    context.rtmt.listenMessage(channel_on_game_user_leave, (message: any) => {
      const userKeyWhoLeave = message;
      setUserKeyWhoLeave(userKeyWhoLeave);
    });
  };

  const updateBoardViewModel = (boardViewModel: BoardViewModel) => {
    boardViewModel.id = v4();
    setBoardId(boardViewModel.id);
    setBoardViewModel(boardViewModel);
  };

  const resetGameState = () => {
    setGame(undefined);
    setCrashMessage(undefined);
    setUserKeyWhoLeave(undefined);
  };

  const getBoardIndex = (index: number) => {
    if(!game) return -1;
    if (userKey === game.player2Id) return index + game.board.pits.length / 2;
    return index;
  };

  React.useEffect(() => {
    setTheme(context.themeManager.theme);
    const pitAnimator = new PitAnimator(context, updateBoardViewModel);
    setPitAnimator(pitAnimator);
    listenMessages(pitAnimator);
    connectToServer("connecting");
    return () => {
      pitAnimator.dispose();
    };
  }, []);

  React.useEffect(() => {
    context.themeManager.onThemeChange = (theme) => {
      setTheme(theme);
      pitAnimator && game && updateBoardViewModel(pitAnimator.getBoardViewModelFromGame(game));
    };
  }, [boardViewModel]);

  const onNewGameClick = () => {
    resetGameState();
    setSearchingOpponent(true);
    context.rtmt.sendMessage("new_game", {});
  };

  const onLeaveGameClick = () => {
    context.rtmt.sendMessage(channel_leave_game, {});
  };

  const onPitSelect = (index: number, pit: Pit) => {
    if(!boardViewModel) return;
    //TODO : stoneCount comes from view model!
    if (pit.stoneCount === 0) {
      //TODO : warn user
      return;
    }
    boardViewModel.pits[getBoardIndex(index)].pitColor =
      context.themeManager.theme.pitSelectedColor;
    updateBoardViewModel(boardViewModel);
    const gameMove: GameMove = { index: index };
    context.rtmt.sendMessage(channel_game_move, gameMove);
  };

  const showConnectionState = connectionState != "connected";

  const connectionStateText = () => {
    let map: { [key: string]: string } = {
      connecting: context.texts.Connecting,
      connected: context.texts.Connected,
      error: context.texts.CannotConnect,
      reconnecting: context.texts.ConnectingAgain,
    };

    return map[connectionState];
  };

  const textColorOnBoard = getColorByBrightness(
    context.themeManager.theme.boardColor,
    context.themeManager.theme.textColor,
    context.themeManager.theme.textLightColor
  );

  return (
    <PageContainer theme={theme!}>
      <FloatingPanel context={context} color={context.themeManager.theme.boardColor} visible={showConnectionState}>
        <span style={{ color: textColorOnBoard }}>{connectionStateText()}</span>
      </FloatingPanel>
      <HeaderBar
        context={context}
        game={game}
        userKeyWhoLeave={userKeyWhoLeave}
        crashMessage={crashMessage}
        onNewGameClick={onNewGameClick}
        onLeaveGameClick={onLeaveGameClick} />
      <InfoPanel
        context={context}
        game={game}
        crashMessage={crashMessage}
        userKey={userKey}
        userKeyWhoLeave={userKeyWhoLeave}
        searchingOpponent={searchingOpponent} />
      {game && boardViewModel && userKey && (
        <BoardView
          userKey={userKey}
          game={game}
          boardId={boardId}
          boardViewModel={boardViewModel}
          context={context}
          onPitSelect={onPitSelect} />
      )}
    </PageContainer>
  );
};

export default Home;
