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

    // Now let's prepare next turn
    /** @type {import('type/game').TH_PlayerActions} */
    let playerAvailActions = {
      canDrawCards: 3,
      canPass: false,
      canEndTurn: false
    };
    gameData.bluePlayer.playerAvailActions = Object.assign(
      {},
      playerAvailActions
    );
    gameData.redPlayer.playerAvailActions = Object.assign(
      {},
      playerAvailActions
    );
    gameData.game['waitingFor/blue'] = true;
    gameData.game['waitingFor/red'] = true;
    gameData.game.currentPlayer = 'both';
    let instructions =
      'Draw 3 cards. You can replace up to 3 cards (or none if of you want) by placing them at the bottom of your pile';
    gameData.bluePlayer.instructions = instructions;
    gameData.redPlayer.instructions = instructions;
    gameData.game.updatePlayerState = 'both';
    duelCtrl.storeData(gameData);
  };

  this.update = (
    /**@type {import('type/comm').TH_MessageReplace3CardsStep} */ payload = null
  ) => {
    /**@type {import('type/game').TH_GameDataStore} */
    let gameData = duelCtrl.getGameData();
    if (payload) {
      let player = payload.color + 'Player';
      if (payload.heroesInHand.length === 3) {
        duelCtrl.sendChat(
          gameData[player].name,
          `I did not change any cards in my hand !`
        );
      } else {
        let nbCardsToReplace = 3 - payload.heroesInHand.length;
        duelCtrl.sendChat(
          gameData[player].name,
          `I replaced ${nbCardsToReplace} cards in my hand !`
        );
        for (let index = 0; index < nbCardsToReplace; index++) {
          let hero = payload.heroesInPile.shift();
          payload.heroesInHand.push(hero);
        }
      }
      gameData[player].heroesInHand = payload.heroesInHand;
      gameData[player].heroesInPile = payload.heroesInPile;

      gameData[player].playerAvailActions.canDrawCards = 0;
      gameData.game['waitingFor/' + payload.color] = false;
    }

    if (
      gameData.game['waitingFor/blue'] === false &&
      gameData.game['waitingFor/red'] === false
    ) {
      gameData.game.updatePlayerState = 'both';
      let instructions =
        'Wait for the next step to be coded by the developers...';
      gameData.bluePlayer.instructions = instructions;
      gameData.redPlayer.instructions = instructions;
      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 : 3...');

    // duelCtrl.setCurrentState('3...');
    // duelCtrl.startCurrentState();
  };
}
