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

#include "card.h"

void holdemRenderCardInit() {
  tilesetdiv_t *cardBack;

  // Load Cards Texture
  GAME_STATE.cardTexture = assetTextureLoad("cards_normal.png");
  GAME_STATE.cardTileset = tilesetCreate(CARD_COUNT_PER_SUIT, 6,
    GAME_STATE.cardTexture->width, GAME_STATE.cardTexture->height,
    0, 0, 0, 0
  );

  // Cards Primitive
  cardBack = GAME_STATE.cardTileset->divisions+(
    GAME_STATE.cardTileset->columns * 4
  );
  GAME_STATE.cardPrimitive = primitiveCreate(
    QUAD_VERTICE_COUNT * 2, QUAD_INDICE_COUNT * 2
  );
  quadBuffer(GAME_STATE.cardPrimitive, -HOLDEM_GAME_CARD_DEPTH,
    -HOLDEM_GAME_CARD_WIDTH, -HOLDEM_GAME_CARD_HEIGHT,
    cardBack->x0, cardBack->y1,
    HOLDEM_GAME_CARD_WIDTH, HOLDEM_GAME_CARD_HEIGHT,
    cardBack->x1, cardBack->y0,
    QUAD_VERTICE_COUNT, QUAD_INDICE_COUNT
  );
}

pokerposition_t holdemRenderCardGetPosition(uint8_t seat, uint8_t slot) {
  pokerposition_t position;
  float t, t2;

  position.yaw = HOLDEM_GAME_SEAT_ANGLE(seat);
  position.x = sin(position.yaw) * -0.75;
  position.z = cos(position.yaw) * -0.75;

  t = position.yaw + mathDeg2Rad(90);

  switch (slot) {
    case HOLDEM_GAME_CARD_SLOT_HAND0:
    case HOLDEM_GAME_CARD_SLOT_HAND1:
      t2 = HOLDEM_GAME_CARD_WIDTH+HOLDEM_GAME_CARD_PADDING;
      if(slot == HOLDEM_GAME_CARD_SLOT_HAND0) t2 = -t2;
      t2 += 0.1;
      break;
      
    case HOLDEM_GAME_CARD_SLOT_FLOP0:
    case HOLDEM_GAME_CARD_SLOT_FLOP1:
    case HOLDEM_GAME_CARD_SLOT_FLOP2:
    case HOLDEM_GAME_CARD_SLOT_FLOP3:
    case HOLDEM_GAME_CARD_SLOT_FLOP4:
      t2 = HOLDEM_GAME_CARD_WIDTH*2+HOLDEM_GAME_CARD_PADDING;
      t2 = (
        -t2 * ( HOLDEM_GAME_CARD_SLOT_FLOP4-HOLDEM_GAME_CARD_SLOT_FLOP0)
      )/2 + t2*(slot-HOLDEM_GAME_CARD_SLOT_FLOP0);
      break;

    default:
      break;
  }

  position.x += t2 * sin(t);
  position.z += t2 * cos(t);
  
  return position;
}

void holdemRenderCard(card_t card, float x, float y, float z,
  float pitch, float yaw, float roll
) {
  tilesetdiv_t *cardFront = GAME_STATE.cardTileset->divisions + card;
  quadBuffer(GAME_STATE.cardPrimitive, HOLDEM_GAME_CARD_DEPTH,
    -HOLDEM_GAME_CARD_WIDTH, -HOLDEM_GAME_CARD_HEIGHT, 
    cardFront->x0, cardFront->y1,
    HOLDEM_GAME_CARD_WIDTH, HOLDEM_GAME_CARD_HEIGHT,
    cardFront->x1, cardFront->y0,
    0, 0
  );

  shaderUseTexture(GAME_STATE.shaderWorld, GAME_STATE.cardTexture);
  shaderUsePosition(GAME_STATE.shaderWorld, x,y,z, pitch,yaw,roll);
  primitiveDraw(GAME_STATE.cardPrimitive, 0, -1);
}

void holdemRenderCardForSeat(uint8_t seat, card_t card, uint8_t slot) {
  pokerposition_t position = holdemRenderCardGetPosition(seat, slot);
  holdemRenderCard(card, position.x, 0, position.z, mathDeg2Rad(-90), position.yaw, 0);
}