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

#include "dealer.h"

void pokerDealerSet(poker_t *poker, uint8_t dealer) {
  uint8_t i, k;
  pokerplayer_t *player;
  bool foundDealer;
  bool foundSmall;

  foundDealer = false;
  foundSmall = false;
  poker->playerDealer = dealer;

  for(i = 0; i < poker->playerCount; i++) {
    k = (dealer + i) % poker->playerCount;
    player = poker->players + k;
    if(player->state & POKER_PLAYER_STATE_OUT) continue;
    if(!foundDealer) {
      poker->playerDealer = k;
      foundDealer = true;
    } else if(!foundSmall) {
      poker->playerSmallBlind = k;
      foundSmall = true;
    } else {
      poker->playerBigBlind = k;
      break;
    }
  }
}

void pokerDealerNew(poker_t *poker) {
  pokerDealerSet(poker, poker->playerDealer + 1);
}

void pokerDealerTurn(poker_t *poker, uint8_t count) {
  uint8_t i;
  for(i = 0; i < count; i++) {
    cardDeal(
      poker->deck, &poker->deckSize, poker->community, &poker->communitySize
    );
  }
}

void pokerDealerBurn(poker_t *poker, uint8_t count) {
  uint8_t i;
  for(i = 0; i < count; i++) {
    cardDeal(poker->deck, &poker->deckSize, poker->grave, &poker->graveSize);
  }
}

void pokerDeal(poker_t *poker, pokerplayer_t *player, uint8_t count) {
  uint8_t i;
  for(i = 0; i < count; i++) {
    cardDeal(poker->deck, &poker->deckSize, player->cards, &player->cardCount);
  }
}

void pokerDealAllPlayers(poker_t *poker, uint8_t count) {
  uint8_t i, j;
  pokerplayer_t *player;

  for(j = 0; j < count; j++) {
    for(i = 0; i < poker->playerCount; i++) {
      player = poker->players + i;
      
      // Can't deal to a player who is folded or out
      if(player->state & (POKER_PLAYER_STATE_FOLDED|POKER_PLAYER_STATE_OUT)) {
        continue;
      }

      pokerDeal(poker, player, 1);
    }
  }
}
