#include "snake.h"


int main(int argc, char *args[]) {

  /* command argument handling */

  if (argc > 1) {
    if (argc > 2) {
      printf("Too many parameters\n");
      goto help_info;
    }

    if (!strcmp(args[1], "-h") || !strcmp(args[1], "--help")) {

      printf("This is a small TUI snake game.\n\n");
      printf("Controls: Arrow keys/WASD to control the snake.\n");
      printf("          P/Enter to pause.\n");
      printf("          Q to quit.\n");

      return 0;
    }

    printf("Argument \"%s\" not recognized\n", args[1]);

  help_info:
    printf("Try \"-h\" or \"--help\" for more information\n");
    return 1;
  }

  
  /* game settings */

  speed game_speed = AVERAGE;
  selected game_size = {WIDTH, HEIGHT};


  char *env;
  char file_path[PATH_LEN];


  if ((env = getenv("XDG_DATA_HOME")) == NULL) {
    if ((env = getenv("HOME")) == NULL) {
      printf("are you ok?\n");
      return 1;
    }
    
    char local[] = ".local";
    char share[] = "share";

  
    uint8_t error = 0;

    snprintf(file_path, sizeof(file_path), "%s/%s", env, local);
    error += make_folder(file_path);

    snprintf(file_path, sizeof(file_path), "%s/%s/%s", env, local, share);
    error += make_folder(file_path);

    if (error <= 1) {
      printf("Failed to create Folder");
      return 1;
    }

    snprintf(file_path, sizeof(file_path), "%s/%s/%s/%s", env, local, share, SETTING_FILE);
    
  } else {
    snprintf(file_path, sizeof(file_path), "%s/%s", env, SETTING_FILE);
  }

  {
    FILE* setting_file = fopen(file_path, "r");

    if (setting_file != NULL) {
      
      char setting_input[STRING_LEN]; 
      char *endptr;

      fgets(setting_input, sizeof(setting_input), setting_file);

      int32_t number = strtol(setting_input, &endptr, 10);

      if (setting_input != endptr) {
        if (number >= 0 && number < SPEED_L)
          game_speed = number;
      }


      fgets(setting_input, sizeof(setting_input), setting_file);

      number = strtol(setting_input, &endptr, 10);

      if (setting_input != endptr) {
        if (number >= MIN_SIZE && number <= MAX_SIZE)
          game_size.x = number;
      }


      fgets(setting_input, sizeof(setting_input), setting_file);

      number = strtol(setting_input, &endptr, 10);

      if (setting_input != endptr) {
        if (number >= MIN_SIZE && number <= MAX_SIZE)
          game_size.y = number;
      }

      fclose(setting_file);
    }
  } 

  /* Setting up terminal with termios */

  struct termios old, new;

  tcgetattr(STDIN_FILENO, &old);

  new = old;

  new.c_lflag &= ~(ECHO | ICANON);
  new.c_cc[VMIN] = 0;
  new.c_cc[VTIME] = 0;

  tcsetattr(STDIN_FILENO, TCSANOW, &new);

  srand(time(NULL));

  printf("\033[?25l");

  struct winsize init_size, current_size;
  ioctl(STDOUT_FILENO, TIOCGWINSZ, &init_size);
  current_size = init_size;
  bool too_small = false;


  struct timespec mili100 = {0, 1000000 * 100};


  /* Animation at the start */
  if (!start_animation())
    goto end_of_program;


  /* Menu */

  bool menu = true;
  bool setting = false;
  bool change_menu = true;

  main_menu selected_menu = NEW_GAME;
  settings selected_setting = HEIGHT_S;

  while (menu) {

    direction pressed_key = DIRECTIONS;

    char string[STRING_LEN] = {};
    ssize_t length_string = read(STDIN_FILENO, string, sizeof(string) - 1);


    ioctl(STDOUT_FILENO, TIOCGWINSZ, &current_size);

    if (current_size.ws_col != init_size.ws_col ||
        current_size.ws_row != init_size.ws_row) {
      init_size = current_size;
      change_menu = true;
    }


    if (length_string > 0) {
      string[length_string] = '\0';

      pressed_key = read_direction(string, false);
    }

    if (pressed_key == Q_KEY)
      goto end_of_program;


    if (!setting) {
      
      if (!too_small) {
        switch (pressed_key) {
          case UP:
            selected_menu = (selected_menu + (MAIN_MENU - 1)) % MAIN_MENU;
            change_menu = true;
            break;
          case DOWN:
            selected_menu = (selected_menu + 1) % MAIN_MENU;
            change_menu = true;
            break;
          default:
            break;
        }
      }

      if (change_menu) {
        too_small = draw_menu(selected_menu, init_size);
        change_menu = false;
      }

      if (pressed_key == ENTER && !too_small) {
        switch (selected_menu) {
        case NEW_GAME:
          menu = false;
          break;
        case SETTINGS:
          setting = true;
          change_menu = true;
          break;
        default:
          goto end_of_program; 
          break;
        }
      }

    } else {

      /* Settings Menu */

      if (change_menu) {
        
        draw_settings(selected_setting, game_speed, game_size);

        change_menu = false;
      }


      if (pressed_key < DIRECTIONS) {

        int8_t setting_change = 0;

        switch (pressed_key) {
          case UP:
            selected_setting = (selected_setting + (SETTINGS_MENU - 1)) % SETTINGS_MENU;
            break;
          case DOWN:
            selected_setting = (selected_setting + 1) % SETTINGS_MENU;
            break;
          case LEFT:
            setting_change = 1;
            break;
          case RIGHT:
            setting_change = -1;
            break;
          default:
            break;
        }
        
        if (setting_change) {
          switch (selected_setting) {
            case SPEED_S:
              if (
                game_speed + setting_change <= SPEED_L - 1 &&
                ((int8_t) game_speed) + setting_change >= 0 
              ) {
                game_speed += setting_change;
              }
              break;
            case WIDTH_S:
              if (
                game_size.x - setting_change >= MIN_SIZE &&
                game_size.x - setting_change <= MAX_SIZE
              ) {
                game_size.x -= setting_change;
              }
              break;
            case HEIGHT_S:
              if (
                game_size.y - setting_change >= MIN_SIZE &&
                game_size.y - setting_change <= MAX_SIZE
              ) {
                game_size.y -= setting_change;
              }
              break;
            default:
              break;
          }
        }

        change_menu = true;

      }

      if (pressed_key == ENTER) {
        switch (selected_setting) {
          case BACK_S:
            setting = false;
            break;
          default:
            break;
        }
        change_menu = true;
      }
    }

  nanosleep(&mili100, NULL);
  }

  /* initialisation of the game */

  snake my_snake;
  my_snake.length = STARTING_LENGTH;

  my_snake.position = malloc((my_snake.length + 1) * sizeof(snake_part));

  direction shift = RIGHT;
  direction tmp_direction = shift;

  {
    uint16_t i;

    my_snake.position[0].coords.y = game_size.y >> 1;
    my_snake.position[0].coords.x = game_size.x >> 1;
    my_snake.position[0].directions[0] = shift;
    my_snake.position[0].directions[1] = shift;
    for (i = 1; i <= my_snake.length; i++) {
      my_snake.position[i].coords.y = -1;
      my_snake.position[i].coords.x = -1;
    }
  }

  board_state **board = malloc(game_size.y * sizeof(board_state*));
  board_state *values = calloc(game_size.y * game_size.x, sizeof(board_state));

  if(board == NULL || values == NULL)
    goto end_of_program;

  {
    uint8_t i;

    for (i = 0; i < game_size.y; i++)
      board[i] = values + i * game_size.x;
  }

  update_field(my_snake, game_size, board, true);

  bool paused = false;

  uint16_t score = 0;

  if ((too_small = draw_board(game_size, board, current_size, true, false, score)))
    paused = true;


  struct timespec milispeed = {0, 1000000 * (SPEED + game_speed * 25)};

  bool run = true;

  /* start of the actual game loop */

  while (run) {

    /* input handling  */

    
      char string[STRING_LEN] = {};
      ssize_t length_string = read(STDIN_FILENO, string, sizeof(string) - 1);

      if (length_string > 0) {
        string[length_string] = '\0';

        if (!too_small) {
          if (toupper(string[0]) == 'P' || string[0] == '\n') {
            paused = !paused;
            if (paused)
              draw_board(game_size, board, current_size, true, paused, score);
          }

          if (!paused)
            tmp_direction = read_direction(string, true);
        }

        if (toupper(string[0]) == 'Q')
          run = false;
      }
    

    /* game logic */

    /*
    struct timeval current;
    gettimeofday(&current, NULL);*/

    if (/*time_diff >= SPEED * 1000*/ true) {

      ioctl(STDOUT_FILENO, TIOCGWINSZ, &current_size);

      if (current_size.ws_col != init_size.ws_col ||
          current_size.ws_row != init_size.ws_row) {
        init_size = current_size;

        paused = true;
        too_small = draw_board(game_size, board, current_size, true, paused, score);
      }

      if (!paused) {

        if (tmp_direction < DIRECTIONS &&
            ((shift + (DIRECTIONS >> 1)) % DIRECTIONS) != tmp_direction) {
          shift = tmp_direction;
        }

        uint8_t update = update_snake(game_size ,&my_snake, shift);

        uint8_t head_y = my_snake.position[0].coords.y;
        uint8_t head_x = my_snake.position[0].coords.x;

        if (board[head_y][head_x] == FRUIT) {
          my_snake.length++;
          score += 1 + 
            (((MAX_SIZE >> 1) / (game_size.y) + 
            (MAX_SIZE >> 1) / (game_size.x) + 
            (my_snake.length - STARTING_LENGTH)) / (game_speed + 1));
          snake_part *tmp = realloc(my_snake.position, (my_snake.length + 1) * sizeof(snake_part));
          if (tmp == NULL)
            goto end_free;
          my_snake.position = tmp;

          my_snake.position[my_snake.length].coords.y = -1;
          my_snake.position[my_snake.length].coords.x = -1;
        }

        update_field(my_snake, game_size, board, false);

        draw_board(game_size, board, current_size, false, false, score);

        switch (update) {
          case 0: 
            printf("\nERROR\n");
            goto end_free;
            break;
          case 2:
            printf("\nHAHA LOST, LOSER");
            goto end_free;
            break;
          default:
            break;
        }

      }
    }
    nanosleep(&milispeed, NULL);
  }

end_free:

    free(my_snake.position);
    free(board);
    free(values);

end_of_program:

  tcsetattr(STDIN_FILENO, TCSANOW, &old);
  printf("\033[?25h\n\n");

  printf("\033[32m");
  printf("\033[2J\033[H");


  {
    FILE* setting_file = fopen(file_path, "w");

    fprintf(setting_file, "%d\n%d\n%d", game_speed, game_size.x, game_size.y);
  }
  
  return 0;
}
