#include <stdlib.h>

#include "../include/door.h"
#include "../include/const.h"

door_t *door_create(pos_t pos) {
  door_t *door = malloc(sizeof(door_t));
  door->pos = pos;
  door->is_locked = true;
  door->countdown = 0;
  return door;
}

void door_update(door_t *door, game_t *game) {
  (void) game;
  if (door->countdown > 0) {
    door->countdown--;
  }
}

void door_draw(door_t *door, game_t *game) {
  if (door->is_locked) {
    DrawTextureRec(game->assets.tiles, texture_rect(1, 2, TILE_WIDTH, TILE_HEIGHT), (pos_t) { door->pos.x, door->pos.y - TILE_HEIGHT }, WHITE);
    DrawTextureRec(game->assets.tiles, texture_rect(1, 3, TILE_WIDTH, TILE_HEIGHT), door->pos, WHITE);
    if (door->countdown > 0) {
      pos_t lock_pos = {
        .x = door->pos.x,
        .y = door->pos.y - 2 * TILE_HEIGHT,
      };
      DrawTextureRec(game->assets.tiles, texture_rect(3, 1, TILE_WIDTH, TILE_HEIGHT), lock_pos, WHITE);
    }
  }
  else {
    DrawTextureRec(game->assets.tiles, texture_rect(2, 2, TILE_WIDTH, TILE_HEIGHT), (pos_t) { door->pos.x, door->pos.y - TILE_HEIGHT }, WHITE);
    DrawTextureRec(game->assets.tiles, texture_rect(2, 3, TILE_WIDTH, TILE_HEIGHT), door->pos, WHITE);
  }
}

void door_free(door_t *door) {
  free(door);
}

bool door_unlock(door_t *door, game_t *game) {
  if (!door->is_locked) {
    return true;
  }
  int enemies_len = 0;
  bool gates_frozen = true;
  for (int i = 0; i < game->entities_len; i++) {
    if(game->entities[i].type == ENTITY_ENEMY) {
      enemies_len++;
    }
    if(game->entities[i].type == ENTITY_GATE) {
      if (!game->entities[i].gate->frozen) {
        gates_frozen = false;
      }
    }
  }
  if (enemies_len == 0 && gates_frozen) {
    door->is_locked = false;
    return true;
  }
  door->countdown = DOOR_COUNTDOWN;
  return false;
}
