/**
 * Copyright (c) 2021 Dominic Masters
 * 
 * This software is released under the MIT License.
 * https://opensource.org/licenses/MIT
 */

#include "flop.h"

void _pokerGameActionFlopOnStart(
  queue_t *queue, queueaction_t *action, uint8_t i
) {
  pokergame_t *game = (pokergame_t *)action->data;
  pokerdiscussiondata_t discussion;
  bool hasDoneFlop;

  // Prep convo
  discussion.poker = game;

  // Get how many players are left in the round.
  if(pokerInRoundGetCount(&game->poker) > 1) {// Still more than 1
    // Reset all the players
    pokerResetBettingRound(&game->poker);

    // Do actual flop action
    hasDoneFlop = true;
    switch(game->poker.communitySize) {
      case 0x00:
        pokerDealerBurn(&game->poker, POKER_FLOP_BURN_COUNT);
        pokerDealerTurn(&game->poker, POKER_FLOP_CARD_COUNT);
        break;
      case POKER_FLOP_CARD_COUNT:
        pokerDealerBurn(&game->poker, POKER_FLOP_BURN_COUNT);
        pokerDealerTurn(&game->poker, POKER_TURN_CARD_COUNT);
        break;
      case POKER_FLOP_CARD_COUNT+POKER_TURN_CARD_COUNT:
        pokerDealerBurn(&game->poker, POKER_FLOP_BURN_COUNT);
        pokerDealerTurn(&game->poker, POKER_RIVER_CARD_COUNT);
        break;
      default:
        hasDoneFlop = false;
        break;
    }

    // Is there any flop "left to do" ?
    if(hasDoneFlop) {
      // Talk about it.
      discussion.reason = POKER_DISCUSSION_REASON_FLOP;
      pokerDiscussionQueue(&discussion);
      
      // Now, get the count of players left to bet. If "everyone is all in" then
      // this will be 0 and no actual betting needs to happen.
      if(pokerBetGetRemainingBetterCount(&game->poker) > 0x01) {
        // Begin betting.
        game->poker.better = pokerBetGetNextPlayer(&game->poker);
        pokerGameActionLookAdd(game, game->poker.better);
        pokerGameActionBetAdd(game);
      } else {
        //No actual players to bet, so add the following flop instead.
        pokerGameActionFlopAdd(game);
      }

      // Do next action.
      queueNext(queue);
      return;
    }
  }

  // Done betting
  pokerGameActionRestackAdd(game);
  pokerGameActionWinnerAdd(game);

  // Do next action
  queueNext(queue);
}

queueaction_t * pokerGameActionFlopAdd(pokergame_t *game) {
  queueaction_t *action = pokerGameActionAdd(game);
  action->onStart = &_pokerGameActionFlopOnStart;
  return action;
}