#include "gui.hpp"
#include "dinkyecs.hpp"
#include "systems.hpp"
#include "events.hpp"
#include "components.hpp"
#include "dbc.hpp"
#include "collider.hpp"
#include "render.hpp"
#include "save.hpp"
#include "lights.hpp"
#include "ftxui/screen/terminal.hpp"  // for SetColorSupport, Color, TrueColor
#include <filesystem>
#include <fcntl.h>

#if defined(_WIN64) || defined(_WIN32)
 #include <io.h>
#endif

using namespace ftxui;
using lighting::LightSource;
namespace fs = std::filesystem;

/*
 * This needs to be turned into a real world generator
 * system.
 */
void configure_world(DinkyECS::World &world, Map &game_map) {
  const auto &config = world.get_the<MapConfig>();
  // configure a player as a fact of the world
  Player player{world.entity()};
  world.set_the<Player>(player);

  world.set<Position>(player.entity, {game_map.place_entity(0)});
  world.set<Motion>(player.entity, {0, 0});
  world.set<Combat>(player.entity, {100, 10});
  world.set<Tile>(player.entity, {config.PLAYER_TILE});
  world.set<Inventory>(player.entity, {5});
  world.set<LightSource>(player.entity, {5,2});

  auto enemy = world.entity();
  world.set<Position>(enemy, {game_map.place_entity(1)});
  world.set<Motion>(enemy, {0,0});
  world.set<Combat>(enemy, {20, 10});
  world.set<Tile>(enemy, {config.ENEMY_TILE});

  auto enemy2 = world.entity();
  world.set<Position>(enemy2, {game_map.place_entity(2)});
  world.set<Motion>(enemy2, {0,0});
  world.set<Combat>(enemy2, {20, 10});
  world.set<Tile>(enemy2, {"*"});
  world.set<LightSource>(enemy2, {6,1});

  auto gold = world.entity();
  world.set<Position>(gold, {game_map.place_entity(3)});
  world.set<Loot>(gold, {100});
  world.set<Tile>(gold, {"$"});


  auto wall_torch = world.entity();
  world.set<Position>(wall_torch, {game_map.place_entity(4)});
  world.set<LightSource>(wall_torch, {2,3});
  world.set<Tile>(wall_torch, {"!"});
}

const int GAME_MAP_X = 40;
const int GAME_MAP_Y = 40;

int main(int argc, char *argv[]) {
#if defined(_WIN64) || defined(_WIN32)
  _setmode(_fileno(stdout), _O_U16TEXT);
#endif
  DinkyECS::World world;

  Map game_map(GAME_MAP_X, GAME_MAP_Y);

  save::load_configs(world);

  if(argc == 2) {
    fmt::println("Loading save file {}", argv[1]);
    fs::path save_path{argv[1]};
    save::from_file(save_path, world, game_map);
  } else {
    game_map.generate();
    configure_world(world, game_map);
  }

  spatial_map collider;
  world.set_the<spatial_map>(collider);
  System::init_positions(world);

  GUI gui(world, game_map);

  return gui.main();
}
