#include "init.hpp"
#include "color.h"
#include "main.hpp"
#include <csignal>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <nlohmann/json.hpp>
#include <ostream>
#include <string>

using json = nlohmann::json;

void init_entity(Entity &entity, SDL_Renderer *renderer, std::string type,
                 std::string name) {
  json entities;
  try {
    std::ifstream entitiesF("./assets/entities.json");
    entities = json::parse(entitiesF);

  } catch (const json::parse_error &e) {
    std::cerr << "Parse error: " << e.what() << "\n";
    exit(1);
  } catch (const std::exception &e) {
    std::cerr << "Error: " << e.what() << "\n";
    exit(2);
  }

  loaded_entities.push_back(&entity);
  std::clog << entities[type];

  entity.texture = IMG_LoadTexture(
      renderer, entities[type][name]["texture"].get<std::string>().c_str());

  if (entity.texture == NULL) {
    std::cerr << "\n" << RED "[ERROR]" << RESET " failed to load texture\n";
    exit(ENOENT);
  }

  entity.srcRect = {0, 0, entities[type][name]["width"].get<int>(),
                    entities[type][name]["height"].get<int>()};

  entity.speed = entities[type][name]["speed"].get<float>();
}
