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

#include "chess.h"
#include "utils.h"
#include "image.h"

void create_position_image(const struct t_position position)
{
  int x, y, i;
  
  create_images();
  
  cairo_surface_t* chessboard_sfc = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 11 * 36, 9 * 36);
  cairo_t* chessboard_ctx = cairo_create(chessboard_sfc);
  
  cairo_select_font_face(chessboard_ctx, CHESSBOARD_FONT, CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
  cairo_set_font_size(chessboard_ctx, 12);
  
  cairo_set_source_rgb(chessboard_ctx, BORDER_COLOR);
  cairo_paint(chessboard_ctx);
  
  draw_empty_chessboard(chessboard_ctx);
  
  /*
  draw_chesspiece(chessboard_ctx, 'A', 36 * 0 + 18, 36 * (7 - 7) + 18);
  draw_chesspiece(chessboard_ctx, 'a', 36 * 1 + 18, 36 * (7 - 7) + 18);
  draw_chesspiece(chessboard_ctx, 'B', 36 * 1 + 18, 36 * (7 - 6) + 18);
  */
  
  for (y = 7; y >= 0; y --)
  {
    for (x = 0; x <= 9; x ++)
    {
      i = xy2sqr(x, y);
      if (position.board[i] != EMPTY_SQUARE && position.board[i] != BORDER)
      {
        draw_chesspiece(chessboard_ctx, position.board[i], 36 * x + 18, 36 * (7 - y) + 18);
      }
    }
  }
  
  cairo_destroy(chessboard_ctx);
  cairo_surface_write_to_png(chessboard_sfc, "demo_image2.png");
  
  free_images();
  
  cairo_surface_destroy(chessboard_sfc);
}

#define STARTPOS_CLASSICAL "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
#define STARTPOS_CAPABLANCA "rnabqkbcnr/pppppppppp/10/10/10/10/PPPPPPPPPP/RNABQKBCNR w KQkq - 0 1"

int main(int argc, char *argv[])
{
  struct t_position position;
  char fen_i[256];
  const char sample[] = "rnabqkbcnr/pppppppppp/10/10/10/10/PPPPPPPPPP/RNABQKBCNR w KQkq - 0 1";
  struct t_move moves[256];
  int movecount, i;
  char move_str[6];
  struct t_position_info info;
  
  erase_position(&position);
  
  if (argc > 1) { strcpy(fen_i, argv[1]); } else { strcpy(fen_i, sample); }
  load_position_from_fen(&position, fen_i);
  
  prettyprint_position(position);
  printf("\n");
  
  create_position_image(position);
  
  info = get_position_info(&position, 0);
  
  print_info(info);
  printf("\n");
  
  movecount = generate_legal_moves(position, info, moves, sizeof(moves) / sizeof(struct t_move), 0);
  
  for (i = 0; i < movecount; i ++)
  {
    move2str(moves[i], move_str, sizeof(move_str));
    printf("%-6s", move_str);
    if ((i + 1) % 12 == 0 || i == movecount - 1)
    {
      printf("\n");
    }
  }
  
  return 0;
}
