'use strict';
import { getHeroesByFaction, shuffleHeroes } from '../heroesHelper.js';
import stateMixins from './stateMixins.js';
export default function selectFactionState(duelController) {
  stateMixins.call(this);
  let duelCtrl = duelController;
  this.start = () => {
    /** @type {import('type/game').TH_GameDataStore} */
    let gameData = duelCtrl.getGameData();
    gameData.game['waitingFor/blue'] = true;
    gameData.game['waitingFor/red'] = true;
    gameData.game.currentPlayer = 'both';
    let instructions =
      'Select a faction of 12 Heroes between Orcs, Humans, Elves or Mecanics';
    gameData.bluePlayer.instructions = instructions;
    gameData.redPlayer.instructions = instructions;
    gameData.game.updatePlayerState = 'both';
    duelCtrl.storeData(gameData);
  };

  // Should receive in paylod : {color, faction}
  this.update = (
    /** @type {import('type/comm').TH_MessageFaction}*/ payload = null
  ) => {
    /** @type {import('type/game').TH_GameDataStore} */
    let gameData = duelCtrl.getGameData();
    if (payload) {
      let player = payload.color + 'Player';
      gameData[player].faction = payload.faction;

      // Init player twelve heroes
      gameData[player].twelveHeroes = getHeroesByFaction(
        gameData.game.allHeroes,
        payload.faction,
        gameData.game.advRules.includes('popularity')
      );

      // Init player pile and shuffle
      gameData[player].heroesInPile = gameData[player].twelveHeroes.map(
        hero => hero.id
      );
      shuffleHeroes(gameData[player].heroesInPile);

      gameData.game['waitingFor/' + payload.color] = false;
      duelCtrl.sendChat(
        gameData[player].name,
        `I chose the ${payload.faction} faction !`
      );

      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 = '';
        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();
  };
}
