#include "map.h"
#include <ctype.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_BUF_LENGTH 1024
#define MAX_COMBO_LENGTH 1024

int fix_delim(char *command, char *needle) {
  char *delim = strstr(command, needle);

  if (!delim)
    return 0;

  delim[0] = ';';

  return 1;
}

int sort_comp(const void *a, const void *b) {
  return strcmp(*(char **)a, *(char **)b);
}

#if !defined(_WIN32) && (defined(__unix__) || defined(__unix) ||               \
                         (defined(__APPLE__) && defined(__MACH__)))

int inv_handler(const void *key, unsigned long size, unsigned long val,
                void *usr)
#else
int inv_handler(const void *key, unsigned long long size,
                unsigned long long val, void *usr)
#endif
{
  if (val == 0)
    return 0;
  char *key2 = (char *)key;

  if (key2[strlen(key2) - 1] == '\n') {
    printf("- %s", (char *)key);
  } else {
    printf("- %s\n", (char *)key);
  }
  return 1;
}

int slash_command(char *command, hashmap *inv) {

  if (command[0] == '/') {
    command++;
  } else {
    return 0;
  }

  if (strcmp(command, "inv\n") == 0) {
    printf("Your inventory:\n");
    hashmap_iterate(inv, inv_handler, "inv");
  }
  return 1;
}

int get_command(char *command, char *command_re, char **sort_tmp) {

  while (1) {
    int get_out = 0;
    get_out |= fix_delim(command, "+");
    get_out |= fix_delim(command, ",");
    if (!get_out)
      break;
  }

  if (command[0] == ';') {
    command++;
  }

  int cl = strlen(command);

  if (cl < 2)
    return 0;

  command[cl - 1] = '\0';

  for (int i = 0; i < cl - 1; i++) {
    command[i] = tolower(command[i]);
  }

  sort_tmp[0] = command;
  int combos = 0;
  for (int i = 1; i < MAX_COMBO_LENGTH; i++) {
    combos = i;
    sort_tmp[i] = strstr(sort_tmp[i - 1], ";");
    if (sort_tmp[i] == 0 || sort_tmp[i] == sort_tmp[i - 1])
      break;
    if (strlen(sort_tmp[i]) < 2) {
      sort_tmp[i][0] = '\0';
      break;
    }
    sort_tmp[i][0] = '\0';
    sort_tmp[i]++;
  }

  qsort(sort_tmp, combos, sizeof(char *), sort_comp);

  char *command_re_tmp = command_re;
  for (int i = 0; i < combos; i++) {
    if (i != 0) {
      command_re_tmp[0] = ';';
      command_re_tmp++;
    }
    char *last = sort_tmp[i];
    strcpy(command_re_tmp, last);
    command_re_tmp += strlen(last);
  }

  return combos;
}