import type { GameSettings } from '@/scripts/interfaces/GameSettings';
import GameConnection, {
  type GameIdentifier,
  type GameInformationDto,
} from '../signalR/GameConnection';

class LocalGame {
  public _settings: GameSettings;
  public player1: GameConnection;
  public player2: GameConnection;
  private gameId: string = '';

  public gameState: GameInformationDto | undefined;
  public onGameStateChanged?: (gameState: GameInformationDto | undefined) => void;

  constructor(settings: GameSettings) {
    this._settings = settings;

    this.player1 = new GameConnection(settings.playerName1);
    this.player2 = new GameConnection(settings.playerName2 ?? 'Player 2');

    this.player1.onGameStarted = (gameInfo: GameInformationDto) => {
      console.log('Game started for player 1', gameInfo);
      this.updateState(gameInfo);
    };
    
    this.player1.onFieldUpdated = (currentState: GameInformationDto) => {
      if (this.gameState) {
        this.gameState = currentState;
        this.onGameStateChanged?.(this.gameState);
      }
    };

    this.player1.onGameCreated = (gameIdentifier: GameIdentifier) => {
      this.gameId = gameIdentifier.gameId;
      this.player2.joinGame(gameIdentifier.gameCode);
    };

    this.player2.onGameJoined = (gameIdentifier: GameIdentifier) => {
      this.gameId = gameIdentifier.gameId;
    };
  }

  async start() {
    await this.player1.connect();
    await this.player2.connect();

    await this.player1.createGame(this._settings.fieldSize);
  }

  async updateState(gameInfo: GameInformationDto) {
    this.gameState = gameInfo;
    this.onGameStateChanged?.(this.gameState);
  }

  async drop(index: number) {
    if (this.gameState?.currentTurn == 1) {
      this.player1.drop(this.gameId, index);
    } else {
      this.player2.drop(this.gameId, index);
    }
  }
}

export default LocalGame;
