#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "word.h"
#include "game.h"
#include "util.h"

void load_word(Game *g, char *line) {
  char *token = strtok(line, "|");
  Word *word = &g->words->words[g->words->count];
  word->word = malloc(strlen(token) + 1);
  strcpy(word->word, token);

  word->synonyms_count = 0;
  while ((token = strtok(NULL, ",")) != NULL) {
    word->synonyms[word->synonyms_count] = malloc(strlen(token) + 1);
    strcpy(word->synonyms[word->synonyms_count], token);
    word->synonyms_count++;
  }

  g->words->count++;
}

#include "data/words.c"
void game_load_words(Game *g) {
  g->words = malloc(sizeof(Words));
  g->words->count = 0;
  parse_multiline_string(g, data_words_txt, &load_word);
  printf("loaded words\n");
}

Word *find_word(Words *words, char *word_or_syn) {
  for (int i = 0; i < words->count; i++) {
    for (int j = 0; j < words->words[i].synonyms_count; j++) {
      if (strcmp(words->words[i].synonyms[j], word_or_syn) == 0) return &words->words[i];
    }
  }

  printf("Can't find %s\n", word_or_syn);
  return NULL;
}
