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

#pragma once
#include "card.h"

void pokerCardInit(poker_t *poker) {
  tilesetdiv_t *cardBack;

  // Load Cards Texture
  assetTextureLoad(&poker->cardTexture, "cards_normal.png");
  tilesetInit(&poker->cardTileset,
    CARD_COUNT_PER_SUIT, 6,
    poker->cardTexture.width, poker->cardTexture.height,
    0, 0,
    0, 0
  );

  // Cards Primitive
  cardBack = poker->cardTileset.divisions+(poker->cardTileset.columns * 4);
  primitiveInit(&poker->cardPrimitive,
    QUAD_VERTICE_COUNT * 2, QUAD_INDICE_COUNT * 2
  );
  quadBuffer(&poker->cardPrimitive, -POKER_CARD_DEPTH,
    -POKER_CARD_WIDTH, -POKER_CARD_HEIGHT,
    cardBack->x0, cardBack->y1,
    POKER_CARD_WIDTH, POKER_CARD_HEIGHT,
    cardBack->x1, cardBack->y0,
    QUAD_VERTICE_COUNT, QUAD_INDICE_COUNT
  );
}

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

  position.yaw = POKER_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 POKER_CARD_SLOT_HAND0:
    case POKER_CARD_SLOT_HAND1:
      t2 = POKER_CARD_WIDTH+POKER_CARD_PADDING;
      if(slot == POKER_CARD_SLOT_HAND0) t2 = -t2;
      t2 += 0.1;
      break;
      
    case POKER_CARD_SLOT_FLOP0:
    case POKER_CARD_SLOT_FLOP1:
    case POKER_CARD_SLOT_FLOP2:
    case POKER_CARD_SLOT_FLOP3:
    case POKER_CARD_SLOT_FLOP4:
      t2 = POKER_CARD_WIDTH*2+POKER_CARD_PADDING;
      t2 = (
        -t2 * ( POKER_CARD_SLOT_FLOP4-POKER_CARD_SLOT_FLOP0)
      )/2 + t2*(slot-POKER_CARD_SLOT_FLOP0);
      break;

    default:
      break;
  }

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

void pokerCardRender(poker_t *poker, card_t card, float x, float y, float z,
  float pitch, float yaw, float roll
) {
  tilesetdiv_t *cardFront = poker->cardTileset.divisions + card;
  quadBuffer(&poker->cardPrimitive, POKER_CARD_DEPTH,
    -POKER_CARD_WIDTH, -POKER_CARD_HEIGHT, 
    cardFront->x0, cardFront->y1,
    POKER_CARD_WIDTH, POKER_CARD_HEIGHT,
    cardFront->x1, cardFront->y0,
    0, 0
  );

  shaderUseTexture(&poker->shader, &poker->cardTexture);
  shaderUsePosition(&poker->shader, x,y,z, pitch,yaw,roll);
  primitiveDraw(&poker->cardPrimitive, 0, -1);
}

void pokerCardRenderForSeat(poker_t *poker, uint8_t seat, card_t card, uint8_t slot) {
  pokerposition_t position = pokerCardGetPosition(seat, slot);
  pokerCardRender(poker, card,
    position.x, 0, position.z,
    mathDeg2Rad(-90), position.yaw, 0
  );
}