#include "gui/body_ui.hpp"
#include "game/components.hpp"
#include <guecs/ui.hpp>
#include "algos/rand.hpp"
#include <fmt/xchar.h>
#include "gui/guecstra.hpp"
#include "game/systems.hpp"
#include "game/inventory.hpp"
#include "game/level.hpp"

namespace gui {
  using namespace guecs;
  using std::any, std::any_cast, std::string, std::make_any;

  void BodyUI::init(size_t x, size_t y, size_t width, size_t height) {
    $gui.position(x, y, width, height);
    $gui.layout(
        "[head]"
        "[chest]"
        "[stomach]"
        "[right_arm]"
        "[left_arm]"
        "[right_leg]"
        "[left_leg]");

    $gui.set<Background>($gui.MAIN, {$gui.$parser, });

    for(auto& [name, cell] : $gui.cells()) {
      auto gui_id = $gui.entity(name);

      $gui.set<Text>(gui_id, {guecs::to_wstring(name)});
      $gui.set<Meter>(gui_id, {1.0f, THEME.DARK_MID, {}});
    }

    $gui.init();
    update();
  }

  bool BodyUI::mouse(float x, float y, guecs::Modifiers mods) {
    return $gui.mouse(x, y, mods);
  }

  void BodyUI::update() {
    auto world = GameDB::current_world();
    auto& player = world->get_the<components::Player>();
    auto& player_combat = world->get<components::Combat>(player.entity);

    for(auto& [key, value] : player_combat.body_parts) {
      auto gui_id = $gui.entity(key);

      if(auto meter = $gui.get_if<Meter>(gui_id)) {
        meter->percent = float(value) / float(player_combat.max_hp);
      }

      $gui.show_text(key, fmt::format(L"{}: {}", guecs::to_wstring(key), value));
    }
  }

  void BodyUI::render(sf::RenderWindow &window) {
    $gui.render(window);
    // $gui.debug_layout(window);
  }
}
