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

#include "game.h"
#include "game_aux.h"
#include "game_ext.h"
#include "game_tools.h"

int main(int argc, char* argv[]) {
  srand(time(NULL));
  game g;
  if (argc == 2) {
    g = game_load(argv[1]);
  } else if (argc > 2) {
    printf("Usage ./game_text [<filename>] or ./game_text");
    exit(EXIT_FAILURE);
  } else {
    g = game_default();
  }
  while (game_won(g) == false) {
    char input;
    if (input != '\n' && input != ' ') {
      game_print(g);
      printf("> Waiting input [type h for help] \n");
    }
    scanf("%c", &input);
    if (input == 'h') {
      printf(
          "\nCommand list:\n"
          " h = help\n"
          " r = shuffle the grid\n"
          " c <i> <j> = turn the piece a the cordinates (i,j) clockwise \n"
          " a <i> <j> = turn the piece a the cordinates (i,j) anti-clockwise \n"
          " y = redo\n"
          " z = undo\n"
          " q = quit\n"
          " s <filename> = save the current game into the file named "
          "<filename>\n\n");
    } else if (input == 'r') {
      printf("> The game has been shuffled \n");
      game_shuffle_orientation(g);
    } else if (input == 'y') {
      game_redo(g);
    } else if (input == 'z') {
      game_undo(g);
    } else if (input == 'q') {
      printf(
          "\nReally ? You're giving up ?\nWell (╯°□°)╯︵ ┻━┻ shame on you. "
          "-_-\n\n");
      game_delete(g);
      return EXIT_SUCCESS;
    } else if (input == 's') {
      char fileToSave[100];
      scanf("%s", fileToSave);
      game_save(g, fileToSave);

    } else if (input == 'c' || input == 'a') {
      int i;
      int j;
      scanf("%d %d", &i, &j);
      if (input == 'a') {
        game_play_move(g, i, j, -1);
      } else {
        game_play_move(g, i, j, 1);
      }
      printf("> Played the move '%c' at (%d,%d)\n", input, i, j);
    } else if (input != '\n' && input != ' ') {
      printf("Invalid command [type h for help] %c %d\n", input, input);
    }
  }
  game_print(g);
  printf(
      "You won, congratulation ! We're proud of you c:"
      "\nHere is your cookie :\n "
      "⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡴⠚⣉⡙⠲⠦⠤⠤⣤⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"
      "⠀⠀⠀⠀⠀⠀⢀⣴⠛⠉⠉⠀⣾⣷⣿⡆⠀⠀⠀⠐⠛⠿⢟⡲⢦⡀⠀⠀⠀⠀\n"
      "⠀⠀⠀⠀⣠⢞⣭⠎⠀⠀⠀⠀⠘⠛⠛⠀⠀⢀⡀⠀⠀⠀⠀⠈⠓⠿⣄⠀⠀⠀\n"
      "⠀⠀⠀⡜⣱⠋⠀⠀⣠⣤⢄⠀⠀⠀⠀⠀⠀⣿⡟⣆⠀⠀⠀⠀⠀⠀⠻⢷⡄⠀\n"
      "⠀⢀⣜⠜⠁⠀⠀⠀⢿⣿⣷⣵⠀⠀⠀⠀⠀⠿⠿⠿⠀⠀⣴⣶⣦⡀⠀⠰⣹⡆\n"
      "⢀⡞⠆⠀⣀⡀⠀⠀⠘⠛⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢿⣿⣶⠇⠀⢠⢻⡇\n"
      "⢸⠃⠘⣾⣏⡇⠀⠀⠀⠀⠀⠀⠀⡀⠀⠀⠀⠀⠀⠀⣠⣤⣤⡉⠁⠀⠀⠈⠫⣧\n"
      "⡸⡄⠀⠘⠟⠀⠀⠀⠀⠀⠀⣰⣿⣟⢧⠀⠀⠀⠀⠰⡿⣿⣿⢿⠀⠀⣰⣷⢡⢸\n"
      "⣿⡇⠀⠀⠀⣰⣿⡻⡆⠀⠀⠻⣿⣿⣟⠀⠀⠀⠀⠀⠉⠉⠉⠀⠀⠘⢿⡿⣸⡞\n"
      "⠹⣽⣤⣤⣤⣹⣿⡿⠇⠀⠀⠀⠀⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡔⣽⠀\n"
      "⠀⠙⢻⡙⠟⣹⠟⢷⣶⣄⢀⣴⣶⣄⠀⠀⠀⠀⠀⢀⣤⡦⣄⠀⠀⢠⣾⢸⠏⠀\n"
      "⠀⠀⠘⠀⠀⠀⠀⠀⠈⢷⢼⣿⡿⡽⠀⠀⠀⠀⠀⠸⣿⣿⣾⠀⣼⡿⣣⠟⠀⠀\n"
      "⠀⠀⠀⠀⠀⠀⠀⠀⢠⡾⣆⠑⠋⠀⢀⣀⠀⠀⠀⠀⠈⠈⢁⣴⢫⡿⠁⠀⠀⠀\n"
      "⠀⠀⠀⠀⠀⠀⠀⠀⠈⠙⣧⣄⡄⠴⣿⣶⣿⢀⣤⠶⣞⣋⣩⣵⠏⠀⠀⠀⠀⠀\n"
      "⠀⠀⠀⠀⠀⠀⠀⠀⠀⢺⣿⢯⣭⣭⣯⣯⣥⡵⠿⠟⠛⠉⠉⠀⠀⠀⠀⠀⠀⠀\n");
  game_delete(g);
  return EXIT_SUCCESS;
}
