'use strict';
import { shuffleHeroes } from '../heroesHelper.js';
import stateMixins from './stateMixins.js';
export default function selectTournamentState(duelController) {
  stateMixins.call(this);
  let duelCtrl = duelController;
  this.start = () => {
    /** @type {import('type/game').TH_GameDataStore} */
    let gameData = duelCtrl.getGameData();

    gameData.bluePlayer.draftHeroesIds = gameData.game.allHeroes.map(
      hero => hero.id
    );
    gameData.redPlayer.draftHeroesIds = gameData.game.allHeroes.map(
      hero => hero.id
    );
    gameData.game['waitingFor/blue'] = true;
    gameData.game['waitingFor/red'] = true;
    gameData.game.currentPlayer = 'both';
    let instructions = 'Select 12 heroes below to build your game deck';
    gameData.bluePlayer.instructions = instructions;
    gameData.redPlayer.instructions = instructions;
    gameData.game.updatePlayerState = 'both';
    duelCtrl.storeData(gameData);
  };

  this.update = (
    /** @type {import('type/comm').TH_MessageTournamentDeckStep} */ payload = null
  ) => {
    /** @type {import('type/game').TH_GameDataStore} */
    let gameData = duelCtrl.getGameData();
    if (payload) {
      let player = payload.color + 'Player';
      let heroesInPile = [];
      heroesInPile.push(...payload.chosenIds);
      gameData[player].twelveHeroes = gameData.game.allHeroes.filter(hero =>
        heroesInPile.includes(hero.id)
      );

      shuffleHeroes(heroesInPile);
      // Init player twelve heroes
      gameData[player].heroesInPile = heroesInPile;
      gameData.game['waitingFor/' + payload.color] = false;

      if (
        gameData.game['waitingFor/blue'] === false &&
        gameData.game['waitingFor/red'] === false
      ) {
        gameData.game.updatePlayerState = 'both';
        // No need to keep all heroes now for rest of the game
        gameData.game.allHeroes = [];
        // Clean Json file
        gameData.game.allHeroesJson = '';
        //Clean draft Ids
        gameData.bluePlayer.draftHeroesIds = [];
        gameData.redPlayer.draftHeroesIds = [];
        duelCtrl.storeData(gameData);
        duelCtrl.endCurrentState();
      } else {
        gameData.game.updatePlayerState = payload.color;
        // Still waiting for one player
        duelCtrl.storeData(gameData);
      }
    }
  };

  this.end = () => {
    console.log('Go to next game state : 2_CHANGE_UP_TO_3_CARDS');

    duelCtrl.setCurrentState('2_CHANGE_UP_TO_3_CARDS');
    duelCtrl.startCurrentState();
  };
}
