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

#include "game.h"
#include "room_in.h"
#include "util.h"

void load_room_in(Game *g, char *line) {
  RoomIn *ri = &g->room_ins->room_ins[g->room_ins->count];
  ri->predicates_count = 0;

  char *line_token_guy;
  char *line_token = strtok_r(line, "|", &line_token_guy);

  Room *r = find_room(g->rooms, line_token);
  g->room_ins->room_ins[g->room_ins->count].room = r;

  line_token = strtok_r(NULL, "|", &line_token_guy);

  char *room_in_token_guy;
  char room_in_buffer[200];
  strcpy(room_in_buffer, line_token);
  char *room_in_word = strtok_r(room_in_buffer, " &", &room_in_token_guy);
  while (room_in_word != NULL) {
    Predicate *p = create_predicate(g, room_in_word);
    ri->predicates[ri->predicates_count++] = p;
    room_in_word = strtok_r(NULL, " &", &room_in_token_guy);
  }

  line_token = strtok_r(NULL, "|", &line_token_guy);
  ri->priority = atoi(line_token);

  line_token = strtok_r(NULL, "|", &line_token_guy);
  g->room_ins->room_ins[g->room_ins->count].description = malloc(strlen(line_token) + 1);
  strcpy(g->room_ins->room_ins[g->room_ins->count].description, line_token);

  g->room_ins->count++;
}

#include "data/room_ins.c"
void game_load_room_ins(Game *g) {
  g->room_ins = malloc(sizeof(RoomIns));
  g->room_ins->count = 0;
  parse_multiline_string(g, data_room_ins_txt, &load_room_in);
  printf("loaded room ins\n");
}

RoomIn *find_room_in(Game *g) {
  RoomIn *ri;
  int priority = -1;
  bool failed_predicate;
  for (int i = 0; i < g->room_ins->count; i++) {
    RoomIn *cri = &g->room_ins->room_ins[i];
    if (cri->priority < priority) continue;
    if (cri->room != g->current_room) continue;
    failed_predicate = false;

    for (int j = 0; j < cri->predicates_count; j++) {
      if (!predicate_fulfilled(g, cri->predicates[j])) failed_predicate = true;
    }
    if (failed_predicate) break;
    priority = cri->priority;
    ri = cri;
  }

  if (ri) return ri;
  
  printf("Couldn't find a valid room_in\n");
  return &g->room_ins->room_ins[0];
}
