#include "systems.hpp"
#include <fmt/core.h>
#include <string>
#include <cmath>
#include "rand.hpp"
#include "spatialmap.hpp"
#include "events.hpp"
#include "ftxui/screen/color.hpp"
#include "ftxui/screen/terminal.hpp"  // for SetColorSupport, Color, TrueColor
#include "dbc.hpp"
#include "lights.hpp"

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

void System::lighting(DinkyECS::World &world, Map &game_map, LightRender &light) {
  light.reset_light();

  world.query<Position>([&](const auto &ent[[maybe_unused]], auto &position) {
    light.set_light_target(position.location);
  });

  light.path_light(game_map.walls());

  world.query<Position, LightSource>([&](const auto &ent[[maybe_unused]], auto &position, auto &lightsource) {
    light.render_light(lightsource, position.location);
  });
}

void System::enemy_pathing(DinkyECS::World &world, Map &game_map, Player &player) {
  // TODO: this will be on each enemy not a global thing
  const auto &player_position = world.get<Position>(player.entity);
  game_map.set_target(player_position.location);
  game_map.make_paths();

  world.query<Position, Motion>([&](const auto &ent, auto &position, auto &motion) {
    if(ent != player.entity) {
      dbc::check(world.has<EnemyConfig>(ent), "enemy is missing config");
      const auto &config = world.get<EnemyConfig>(ent);

      Point out = position.location; // copy
      if(game_map.distance(out) < config.hearing_distance) {
        game_map.neighbors(out, motion.random);
        motion = { int(out.x - position.location.x), int(out.y - position.location.y)};
      }
    }
  });
  game_map.clear_target(player_position.location);
}

void System::init_positions(DinkyECS::World &world) {
  auto &collider = world.get_the<SpatialMap>();

  // BUG: instead of separate things maybe just one
  // BUG: Collision component that references what is collide
  world.query<Position, Combat>([&](const auto &ent, auto &pos, auto &combat) {
      if(!combat.dead) {
        collider.insert(pos.location, ent);
      }
  });

  world.query<Position>([&](const auto &ent, auto &pos) {
      collider.insert(pos.location, ent);
  });
}

inline void move_entity(SpatialMap &collider, Map &game_map, Position &position, Motion &motion, DinkyECS::Entity ent) {
  Point move_to = {
    position.location.x + motion.dx,
    position.location.y + motion.dy
  };
  motion = {0,0}; // clear it after getting it

  // it's a wall, skip
  if(!game_map.can_move(move_to)) return;
  // there's collision skip
  if(collider.occupied(move_to)) return;

  // all good, do the move
  collider.move(position.location, move_to, ent);
  position.location = move_to;
}

void System::motion(DinkyECS::World &world, Map &game_map) {
  auto &collider = world.get_the<SpatialMap>();

  world.query<Position, Motion>([&](const auto &ent, auto &position, auto &motion) {
    // don't process entities that don't move
    if(motion.dx != 0 || motion.dy != 0) {
      move_entity(collider, game_map, position, motion, ent);
    }
  });
}

void System::death(DinkyECS::World &world) {
  // BUG: this is where entities can die on top of
  // BUG: eachother and overlap their corpse
  // BUG: maybe that can be allowed and looting just shows
  // BUG: all dead things there?
  auto &collider = world.get_the<SpatialMap>();
  auto player = world.get_the<Player>();

  world.query<Position, Combat>([&](const auto &ent, auto &position, auto &combat) {
    // bring out yer dead
    if(combat.hp <= 0 && !combat.dead) {
      combat.dead = true;
      // take them out of collision map
      collider.remove(position.location);

      if(ent == player.entity) {
        world.send<Events::GUI>(Events::GUI::DEATH, ent, {});
      } else {
        // remove their motion so they're dead
        world.remove<Motion>(ent);
      }
    }
  });
}

void System::collision(DinkyECS::World &world, Player &player) {
  auto& collider = world.get_the<SpatialMap>();
  const auto& player_position = world.get<Position>(player.entity);
  auto& player_combat = world.get<Combat>(player.entity);

  // this is guaranteed to not return the given position
  auto [found, nearby] = collider.neighbors(player_position.location);

  if(found) {
    for(auto entity : nearby) {
      if(world.has<Combat>(entity)) {
        auto& enemy_combat = world.get<Combat>(entity);

        Events::Combat result {
          player_combat.attack(enemy_combat),
          enemy_combat.attack(player_combat)
        };

        world.send<Events::GUI>(Events::GUI::COMBAT, entity, result);
      } else if(world.has<InventoryItem>(entity)) {
        auto item = world.get<InventoryItem>(entity);
        auto& item_pos = world.get<Position>(entity);
        auto& inventory = world.get<Inventory>(player.entity);

        if(world.has<LightSource>(entity)) {
          inventory.add(item);
          auto &new_light = world.get<LightSource>(entity);
          world.set<LightSource>(player.entity, new_light);
          inventory.light = new_light;
          world.remove<LightSource>(entity);
        }

        if(world.has<Weapon>(entity)) {
          inventory.add(item);
          auto &weapon = world.get<Weapon>(entity);
          player_combat.damage = weapon.damage;
          world.remove<Weapon>(entity);
        }

        if(world.has<Loot>(entity)) {
          auto &loot = world.get<Loot>(entity);
          inventory.gold += loot.amount;
          world.remove<Loot>(entity);
        }

        if(world.has<Curative>(entity)) {
          auto& cure = world.get<Curative>(entity);
          player_combat.hp += cure.hp;
          world.remove<Curative>(entity);
        }

        collider.remove(item_pos.location);
        world.remove<Tile>(entity);
        world.remove<InventoryItem>(entity);
        world.send<Events::GUI>(Events::GUI::LOOT, entity, item);
      } else {
        println("UNKNOWN COLLISION TYPE {}", entity);
      }
    }
  }
}

void System::draw_entities(DinkyECS::World &world, Map &game_map, const Matrix &lighting, ftxui::Canvas &canvas, const Point &cam_orig, size_t view_x, size_t view_y) {
  auto &tiles = game_map.tiles();

  world.query<Position, Tile>([&](auto &ent[[maybe_unused]], auto &pos, auto &tile) {
    if(pos.location.x >= cam_orig.x && pos.location.x <= cam_orig.x + view_x
        && pos.location.y >= cam_orig.y && pos.location.y <= cam_orig.y + view_y) {
      Point loc = game_map.map_to_camera(pos.location, cam_orig);

      float light_value = lighting[pos.location.y][pos.location.x] * PERCENT;
      const TileCell& cell = tiles.at(pos.location.x, pos.location.y);

      // the 2 and 4 are from ftxui::Canvas since it does a kind of "subpixel" drawing
      canvas.DrawText(loc.x*2, loc.y*4, tile.chr, [light_value, cell](auto &pixel) {
          pixel.foreground_color = Color::HSV(255, 200, 180 * light_value);
          pixel.background_color = Color::HSV(cell.bg_h, cell.bg_s, cell.bg_v * light_value);
      });
    }
  });
}

void System::pickup(DinkyECS::World &world, DinkyECS::Entity actor, DinkyECS::Entity item) {
  dbc::pre("System::pickup actor doesn't have inventory", world.has<Inventory>(actor));
  dbc::pre("System::pickup item isn't configured with InventoryItem.", world.has<InventoryItem>(item));

  auto& inventory = world.get<Inventory>(actor);
  auto& invitem = world.get<InventoryItem>(item);

  inventory.add(invitem);
}
