<script setup lang="ts">
import { ref } from 'vue';
import GameCreationMenu from '@/components/GameCreationMenu.vue';
import type { GameSettings } from '@/scripts/interfaces/GameSettings';
import LocalGame from '@/scripts/logic/localMode/LocalGame';
import Field from '@/components/game/Field.vue';
import InfoField from '@/components/game/InfoField.vue';
import type { GameEnded } from '@/scripts/logic/signalR/GameConnection';
import GameEndedMenu from '@/components/GameEndedMenu.vue';

enum CurrentState {
  CreatingGame,
  Game,
  EndScreen,
}

let settings = ref<GameSettings>({
  playerName1: 'Spieler 1',
  playerName2: 'Spieler 2',
  botPlayer2: false,
  fieldSize: { x: 7, y: 6 },
});

var currentState = ref<CurrentState>(CurrentState.CreatingGame);
const game = ref<LocalGame>(new LocalGame());
const gameField = ref<number[][]>([]);
const currentSelectionIndex = ref<number | null>(null);
const gameEndedInformation = ref<GameEnded | null>(null);

game.value.onGameStateChanged = (gameState) => {
  gameField.value = gameState?.currentField ?? [];
};

game.value.onGameEnded = (gameEndedInfo) => {
  gameEndedInformation.value = gameEndedInfo;
  currentState.value = CurrentState.EndScreen;
};

async function startGame() {
  await game.value.start(settings.value);

  currentState.value = CurrentState.Game;
}

async function restart() {
  await game.value.disconnectAll();

  startGame();
}
</script>

<template>
  <GameCreationMenu
    v-model:settings="settings"
    @create-game="startGame()"
    v-if="currentState === CurrentState.CreatingGame"
  />

  <GameEndedMenu
    :game-ended-information="gameEndedInformation"
    @restart-game="restart"
    v-else-if="currentState === CurrentState.EndScreen"
  ></GameEndedMenu>

  <div id="game" v-else>
    <div class="game-content">
      <Field
        :game-state="gameField"
        v-model:current-selection-index="currentSelectionIndex"
        @click-on-game-field="game.drop(currentSelectionIndex ?? 1)"
      />

      <InfoField :msg="game.currentDescription"></InfoField>
    </div>
  </div>
</template>

<style scoped></style>
