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

#include "poker.h"

void pokerInit(poker_t *poker) {
  poker->playerCount = 0;
  poker->playerDealer = 0;
  poker->playerSmallBlind = 0;
  poker->playerBigBlind = 0;
  pokerResetRound(poker);
  pokerSetBlinds(poker, 0, 0);
}

void pokerSetBlinds(poker_t *poker, int32_t blindSmall, int32_t blindBig) {
  poker->blindSmall = blindSmall;
  poker->blindBig = blindBig;
}

void pokerResetRound(poker_t *poker) {
  uint8_t i;
  pokerplayer_t *player;

  poker->deckSize = cardWriteDeck(poker->deck);
  poker->graveSize = 0;
  poker->communitySize = 0;
  poker->potCount = 0;
  pokerPotAdd(poker);

  pokerResetBettingRound(poker);

  for(i = 0; i < poker->playerCount; i++) {
    player = poker->players + i;
    player->cardCount = 0;
    player->currentBet = 0;
    player->timesRaised = 0;
    player->state &= ~(
      POKER_PLAYER_STATE_FOLDED |
      POKER_PLAYER_STATE_HAS_BET_THIS_ROUND |
      POKER_PLAYER_STATE_SHOWING
    );
  }
}

void pokerResetBettingRound(poker_t *poker) {
  uint8_t i;
  pokerplayer_t *player;

  // Reset the round betting state.
  for(i = 0; i < poker->playerCount; i++) {
    player = poker->players + i;
    player->state =flagOff(player->state,POKER_PLAYER_STATE_HAS_BET_THIS_ROUND);
    player->timesRaised = 0;
  }
  
  // Now reset to the first player that needs to bet.
  if(poker->playerCount > 0) {
    poker->better = (poker->playerBigBlind + 1) % poker->playerCount;
  } else {
    poker->better = 0x00;
  }
  
  // Then we check who's remaining. We do this because the default better may
  // have folded already.
  poker->better = pokerBetGetNextPlayer(poker);
}

void pokerTakeBlinds(poker_t *poker) {
  pokerBetForPlayer(poker, poker->playerSmallBlind, poker->blindSmall);
  pokerBetForPlayer(poker, poker->playerBigBlind, poker->blindBig);
}

uint8_t pokerInRoundGetCount(poker_t *poker) {
  uint8_t i, count;
  pokerplayer_t *player;

  count = 0;
  for(i = 0; i < poker->playerCount; i++) {
    player = poker->players + i;
    if(player->state & (POKER_PLAYER_STATE_FOLDED | POKER_PLAYER_STATE_OUT)) {
      continue;
    }
    count++;
  }

  return count;
}