#include <catch2/catch_test_macros.hpp>
#include <fmt/core.h>
#include "render.hpp"
#include "panel.hpp"
#include "map.hpp"
#include "worldbuilder.hpp"
#include "config.hpp"
#include "components.hpp"
#include "systems.hpp"
#include "save.hpp"

using namespace ftxui;
using namespace fmt;
using namespace components;
using namespace lighting;
using std::string;

void run_renderer(SFMLRender &renderer, Panel &panel) {
  panel.render();
  renderer.display();
  REQUIRE(renderer.is_open() == true);
  renderer.clear();
  renderer.draw(panel);
}

TEST_CASE("can render a text panel", "[render]") {
  SFMLRender renderer;
  renderer.init_terminal();

  Panel panel(0, 0, 20, 5);

  auto text_box = Renderer([]{
      return hbox({
        hflow(
            vbox(text("I AM TEXT"))
        )});
    });

  panel.set_renderer(text_box);
  run_renderer(renderer, panel);
  renderer.close();
}

TEST_CASE("can render a text", "[render]") {
  SFMLRender renderer;
  renderer.init_terminal();
  DinkyECS::World world;

  save::load_configs(world);
  const auto& config = world.get_the<MapConfig>();

  Panel map_view(0, 0, 20, 20, true);
  Map map(20,20);
  WorldBuilder builder(map);
  builder.generate();

  Player player{world.entity()};
  world.set_the<Debug>({});
  world.set_the<Player>(player);
  world.set<Tile>(player.entity, {config.PLAYER_TILE});
  world.set<LightSource>(player.entity, {6,1});

  world.set<Position>(player.entity, {map.place_entity(0)});

  LightRender lights(map.width(), map.height());

  Canvas map_canvas(map_view.width * 2, map_view.height * 4);

  map_view.set_renderer(Renderer([&] {
    System::draw_map(world, map, lights.lighting(), map_canvas, map_view.width, map_view.height);
    return canvas(map_canvas);
  }));

  run_renderer(renderer, map_view);

  for(int i = 2; i < 14; i++) {
    renderer.resize_grid(i * 10, map_view);
    map_canvas = Canvas(map_view.width * 2, map_view.height * 4);
    run_renderer(renderer, map_view);
  }

  renderer.close();
}
