#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>

#include <raylib.h>

#include "card.h"
#include "move.h"
#include "teyaku.h"

char *text = "こんにちわ、 世界!";

int main(int argc, char** argv) {
    InitWindow(800, 550, "Hanafuda Hachi-Hachi");
    SetTargetFPS(60);

    /*
    Hand h;
    h.cards[0] = (Card) { 1, BRIGHT, RIBBON_NONE, NOVEMBER, (Vector2) { 0, 0 } };
    h.cards[1] = (Card) { 1, ANIMAL, RIBBON_NONE, NOVEMBER, (Vector2) { 0, 0 } };
    h.cards[2] = (Card) { 1, RIBBON, RIBBON_PLAIN, NOVEMBER, (Vector2) { 0, 0 } };
    h.cards[3] = (Card) { 1, CHAFF, RIBBON_NONE, NOVEMBER, (Vector2) { 0, 0 } };
    h.cards[4] = (Card) { 1, CHAFF, RIBBON_NONE, DECEMBER, (Vector2) { 0, 0 } };
    h.cards[5] = (Card) { 1, CHAFF, RIBBON_NONE, DECEMBER, (Vector2) { 0, 0 } };
    h.cards[6] = (Card) { 1, CHAFF, RIBBON_NONE, DECEMBER, (Vector2) { 0, 0 } };
    h.count = 7;

    printf("Teyaku: %d\n", calculate_teyaku(h));
    */

    Card cards[48];
    for (int i = 0; i < 48; i++) {
      CardType t = CHAFF;
      RibbonType rt = RIBBON_NONE;
      Month month = i / 4;
      switch (i) {
      case 0:
      case 8:
      case 28:
      case 40:
      case 44:
	t = BRIGHT; break;
      case 1:
      case 5:
      case 9:
	t = RIBBON; rt = RIBBON_POETRY; break;
      case 21:
      case 33:
      case 37:
	t = RIBBON; rt = RIBBON_BLUE; break;
      case 13:
      case 17:
      case 25:
      case 42:
	t = RIBBON; rt = RIBBON_PLAIN; break;
      case 4:
      case 12:
      case 16:
      case 20:
      case 24:
      case 29:
      case 32:
      case 36:
      case 41:
	t = ANIMAL; break;
      }
      cards[i] = (Card) { i, t, rt, month, (Vector2) { month * 65, (i % 4) * 110 }, false };
    }

    float delta;
    Vector2 mouse_position;
    char *calculation = "";

    while (!WindowShouldClose()) {
      delta = GetFrameTime();

      if (IsMouseButtonPressed(0)) {
	Vector2 mouse_pos = GetMousePosition();
	for (int i = 0; i < 48; i++) {
	  if (point_within_card(&cards[i], mouse_pos)) {
	    cards[i].selected = !cards[i].selected;
	    calculation = "";
	    break;
	  }
	}
      }

      BeginDrawing();
      ClearBackground(RAYWHITE);
      int num_selected = 0;
      for (int i = 0; i < 48; i++) {
	num_selected += cards[i].selected;
	draw_card(&cards[i]);
      }

      if (strlen(calculation) == 0 && num_selected == 7) {
	Hand h;
	h.count = 0;
	for (int i = 0; i < 48; i++) {
	  if (cards[i].selected) memcpy(&h.cards[h.count++], &cards[i], sizeof(Card));
	}

	calculation = TextFormat("Set: %s(%d) / Chaff: %s(%d) / Total: %d", set_teyaku_english(h), set_teyaku_points(h), chaff_teyaku_english(h), chaff_teyaku_points(h), calculate_teyaku(h));
      }

      DrawText(calculation, 10, 500, 25, BLACK);
      EndDrawing();
    }
      
    CloseWindow();

    return 0;
}