'use strict';
import { getHeroesIdsByFaction } from '../heroesHelper';

export default function selectFactionState(duelController) {
  let duelCtrl = duelController;
  let 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';
    duelCtrl.storeData(gameData);
  };

  // Should receive in paylod : {color, faction}
  let 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;

      let randomHeroes = getHeroesIdsByFaction(
        gameData.game.allHeroes,
        payload.faction,
        gameData.game.advRules.includes('popularity')
      );
      // Init player twelve heroes
      gameData[player].twelveHeroes = [];
      randomHeroes.forEach(id => {
        gameData[player].twelveHeroes.push({
          id,
          position: 'pile',
          possibleActions: []
        });
      });
      gameData.game['waitingFor/' + payload.color] = false;
      duelCtrl.storeData(gameData);
    }

    if (
      gameData.game['waitingFor/blue'] === false &&
      gameData.game['waitingFor/red'] === false
    ) {
      duelCtrl.endCurrentState();
    }
  };

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

    duelCtrl.setCurrentState('2_CHANGE_UP_TO_3_CARDS');
    duelCtrl.startCurrentState();
  };
  return {
    start,
    update,
    end
  };
}