#include "gui/loot_ui.hpp"
#include "constants.hpp"
#include <fmt/xchar.h>
#include "gui/guecstra.hpp"

namespace gui {
  using namespace guecs;

  LootUI::LootUI(GameLevel level) :
      $level(level)
  {
    $gui.position(RAY_VIEW_X+RAY_VIEW_WIDTH/2-200,
        RAY_VIEW_Y+RAY_VIEW_HEIGHT/2-200, 400, 400);

    $gui.layout(
        "[item_0 | item_1 |item_2 | item_3 ]"
        "[item_4 | item_5 |item_6 | item_7 ]"
        "[item_8 | item_9 |item_10| item_11]"
        "[item_12| item_13|item_14|item_15 ]"
        "[_ | %(100,50)close| _]"
        );
  }

  void LootUI::init() {
    using guecs::THEME;
    auto bg_color = THEME.DARK_LIGHT;
    bg_color.a = 140;
    $gui.set<Background>($gui.MAIN, {$gui.$parser, bg_color});

    auto close = $gui.entity("close");
    $gui.set<guecs::Rectangle>(close, {});
    $gui.set<guecs::Label>(close, {L"CLOSE"});
    $gui.set<guecs::Clickable>(close,
        guecs::make_action(*$level.world, Events::GUI::LOOT_CLOSE));

    for(int i = 0; i < INV_SLOTS; i++) {
      auto id = $gui.entity("item_", i);
      $gui.set<guecs::Rectangle>(id, {THEME.PADDING,
          THEME.TRANSPARENT, THEME.LIGHT_MID });
      $gui.set<guecs::Effect>(id, {0.4f, "ui_shader"});
      $gui.set<guecs::Clickable>(id, {
          guecs::make_action(*$level.world, Events::GUI::LOOT_SELECT, {i})
      });
    }

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

  std::optional<DinkyECS::Entity> LootUI::select_slot(int slot_id) {
    if(slot_id >= 0 && size_t(slot_id) < contents.size()) {
      return contents.at(slot_id);
    } else {
      return std::nullopt;
    }
  }

  shared_ptr<sf::Sprite> LootUI::grab_sprite(int slot_id) {
    auto id = $gui.entity("item_", slot_id);
    auto& sprite = $gui.get<guecs::Sprite>(id);
    return sprite.sprite;
  }

  void LootUI::remove_slot(int slot_id) {
    dbc::check(size_t(slot_id) < contents.size(),
        fmt::format("invalid slot id {} give, contents.size={}",
          slot_id, contents.size()));

    contents.erase(contents.begin() + slot_id);
    update();
  }

  void LootUI::update() {
    dbc::check(contents.size() < INV_SLOTS, "too many items in loot contents, must be < 16");

    for(size_t i = 0; i < INV_SLOTS; i++) {
      auto id = $gui.entity("item_", int(i));

      if($gui.has<guecs::Sprite>(id)) {
        $gui.remove<guecs::Sprite>(id);
      }

      if(i < contents.size()) {
        auto item = contents.at(i);
        auto& sprite = $level.world->get<components::Sprite>(item);
        fmt::println("NEW SPRITE SPRITE {}", sprite.name);
        $gui.set_init<guecs::Sprite>(id, {sprite.name});
      }
    }
  }

  void LootUI::render(sf::RenderWindow& window) {
    $gui.render(window);
  }

  void LootUI::update_level(GameLevel &level) {
    $level = level;
    init();
  }

  bool LootUI::mouse(float x, float y, bool hover) {
    return $gui.mouse(x, y, hover);
  }
}
