#pragma once
#include <vector>
#include <utility>
#include <string>
#include <random>
#include <algorithm>
#include <fmt/core.h>
#include "point.hpp"
#include "tser.hpp"
#include "lights.hpp"

#define INV_WALL 0
#define INV_SPACE 1
#define WALL_VALUE 1
#define SPACE_VALUE 0

using lighting::LightSource;

struct Room {
  size_t x = 0;
  size_t y = 0;
  size_t width = 0;
  size_t height = 0;
  Point entry;
  Point exit;

  DEFINE_SERIALIZABLE(Room, x, y, width, height);
};

typedef std::vector<int> MatrixRow;
typedef std::vector<MatrixRow> Matrix;

void dump_map(const std::string &msg, Matrix &map);
void add_neighbors(Matrix &closed, size_t j, size_t i);

class Map {
public:
  int $limit;
  size_t $width;
  size_t $height;
  Matrix $input_map;
  Matrix $walls;
  Matrix $paths;
  Matrix $lightmap;
  std::vector<Room> $rooms;

  Map(Matrix input_map, Matrix walls_map, int limit);

  // make random
  Map(size_t width, size_t height);

  // disable copying
  Map(Map &map) = delete;

  Matrix& paths() { return $paths; }
  Matrix& lighting() { return $lightmap; }
  Matrix& input_map() { return $input_map; }
  Matrix& walls() { return $walls; }
  int limit() { return $limit; }
  size_t width() { return $width; }
  size_t height() { return $height; }
  int distance(Point to) { return $paths[to.y][to.x]; }

  Room &room(size_t at) { return $rooms[at]; }
  size_t room_count() { return $rooms.size(); }

  void partition_map(Room &cur, int depth);
  void make_room(size_t origin_y, size_t origin_x, size_t width, size_t height);
  void add_door(Room &room);
  bool can_move(Point move_to);
  void generate();
  void place_rooms(Room &root);

  Point place_entity(size_t room_index);
  bool neighbors(Point &out, bool up);
  bool inmap(size_t x, size_t y);
  bool iswall(size_t x, size_t y);
  void make_paths();
  void set_target(const Point &at, int value=0);
  void clear_target(const Point &at);
  bool walk(Point &src, Point &target);
  void set_door(Room &room, int value);

  Point map_to_camera(const Point &loc, const Point &cam_orig);
  Point center_camera(const Point &around, size_t view_x, size_t view_y);
  void reset_light();
  void set_light_target(const Point &at, int value=0);
  void clear_light_target(const Point &at);
  void path_light();
  void light_box(LightSource source, Point from, Point &min_out, Point &max_out);
  int light_level(int level, size_t x, size_t y);
  void render_light(LightSource source, Point at);

  void dump();
};
