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

#include "round.h"

void _pokerActionRoundOnStart(queue_t *queue, queueaction_t *action ,uint8_t i){
  uint8_t j, indexDealer, indexSmallBlind, indexBigBlind;
  bool foundDealer, foundSmallBlind;
  pokerplayer_t *player;
  poker_t *poker;

  poker = (poker_t *)action->data;

  // Prepare the initial game state
  pokerBetReset(&poker->bet);
  pokerDealerInit(&poker->dealer);

  // Reset the players
  for(i = 0; i < POKER_PLAYER_COUNT; i++) {
    pokerPlayerReset(poker->players + i);
  }

  // Decide on the dealer
  poker->roundDealer = (poker->roundDealer+1) % POKER_PLAYER_COUNT;

  // Find the players.
  j = poker->roundDealer;
  foundDealer = false;
  foundSmallBlind = false;
  while(true) {
    player = poker->players + j;
    if(!pokerPlayerIsAlive(player)) continue;
    if(!foundDealer) {
      indexDealer = j;
      foundDealer = true;
    } else if(!foundSmallBlind) {
      indexSmallBlind = j;
      foundSmallBlind = true;
    } else {
      indexBigBlind = j;
      break;
    }
    j = (j + 1) % POKER_PLAYER_COUNT;
  }
  
  // Update players for the round.
  poker->roundDealer = indexDealer;
  poker->roundBigBlind = indexBigBlind;
  poker->roundSmallBlind = indexSmallBlind;

  printf("Round Start\n");
  queueNext(queue);
}

queueaction_t * pokerActionRoundAdd(queue_t *queue, poker_t *poker) {
  queueaction_t *action;
  action = queueAdd(queue);
  action->data = (void *)poker;
  action->onStart = &_pokerActionRoundOnStart;
  return action;
}