#include <catch2/catch_test_macros.hpp>
#include <fmt/core.h>
#include <nlohmann/json.hpp>
#include <fstream>
#include "map.hpp"
#include "levelmanager.hpp"
#include "systems.hpp"

using namespace fmt;
using namespace nlohmann;
using std::string;

json load_test_data(const string &fname) {
  std::ifstream infile(fname);
  return json::parse(infile);
}

TEST_CASE("camera control", "[map]") {
  textures::init();
  components::init();
  LevelManager levels;
  GameLevel level = levels.current();
  auto &map = *level.map;

  Point center = map.center_camera({10,10}, 5, 5);

  map.dump(center.x, center.y);
  REQUIRE(center.x == 8);
  REQUIRE(center.y == 8);

  Point translation = map.map_to_camera({10,10}, center);

  REQUIRE(translation.x == 2);
  REQUIRE(translation.y == 2);
}

TEST_CASE("map placement test", "[map:placement]") {
  textures::init();
  components::init();
  for(int i = 0; i < 20; i++) {
    LevelManager levels;
    GameLevel level = levels.current();
    auto &map = *level.map;

    for(size_t rnum = 0; rnum < map.room_count(); rnum++) {
      Point pos;

      REQUIRE(map.place_entity(rnum, pos));

      REQUIRE(!map.iswall(pos.x, pos.y));
      REQUIRE(map.inmap(pos.x, pos.y));
    }
  }
}

TEST_CASE("dijkstra algo test", "[map]") {
  textures::init();
  json data = load_test_data("./tests/dijkstra.json");

  for(auto &test : data) {
    Matrix expected = test["expected"];
    Matrix input = test["input"];
    Matrix walls = test["walls"];
    Map map(input.size(), input[0].size());
    map.$walls = walls;
    map.$paths.$input = input;

    REQUIRE(map.INVARIANT());

    map.make_paths();
    Matrix &paths = map.paths();

    if(paths != expected) {
      println("ERROR! ------");
      matrix::dump("EXPECTED", expected);
      matrix::dump("RESULT", paths);
    }

    REQUIRE(map.INVARIANT());
    // FIX ME: REQUIRE(paths == expected);
  }
}

TEST_CASE("map image test", "[map-sprite]") {
  components::init();
  textures::init();

  LevelManager levels;
  GameLevel level = levels.current();
  Matrix map_tiles = matrix::make(7,7);
  EntityGrid entity_map;

  auto render = std::make_shared<sf::RenderTexture>();
  sf::Sprite sprite{render->getTexture()};
  auto player = level.world->get_the<components::Player>();
  auto& player_pos = level.world->get<components::Position>(player.entity);
  auto player_display = level.world->get<components::Tile>(player.entity).display;

  for(matrix::each_row it{level.map->walls()}; it.next();) {
    player_pos.location.x = it.x;
    player_pos.location.y = it.y;
    System::draw_map(level, map_tiles, entity_map);
    System::render_map(map_tiles, entity_map, *render, 2, player_display);

#ifdef TEST_RENDER
    // confirm we get two different maps
    auto out_img = render->getTexture().copyToImage();
    bool worked = out_img.saveToFile(fmt::format("tmp/map_render{}{}.png", it.x, it.y));
    REQUIRE(worked);
#endif
  }
}
