#include "gui/overlay_ui.hpp"
#include "gui/guecstra.hpp"
#include "constants.hpp"
#include "events.hpp"
#include <optional>

namespace gui {
  using namespace guecs;

  OverlayUI::OverlayUI() {
    $gui.position(RAY_VIEW_X, RAY_VIEW_Y, RAY_VIEW_WIDTH, RAY_VIEW_HEIGHT);
    $gui.layout(
        "[*%(100,300)left|=top|>(170,170)top_right]"
        "[_|=middle|=middle_right]"
        "[_|=bottom|=bottom_right]"
        );
    $gui.init();
  }

  inline void make_clickable_area(GameLevel& level, guecs::UI &gui, const std::string &name) {
    auto area = gui.entity(name);

    gui.set<Clickable>(area, {
      [&](auto ent, auto data) {
        level.world->send<Events::GUI>(Events::GUI::AIM_CLICK, ent, data);
      }
    });
  }

  void OverlayUI::init() {
    // gui.init is in the constructor
    make_clickable_area($level, $gui, "top");
    make_clickable_area($level, $gui, "middle");
    make_clickable_area($level, $gui, "bottom");
  }

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

  void OverlayUI::show_sprite(string region, string sprite_name) {
    $gui.show_sprite(region, sprite_name);
  }

  void OverlayUI::close_sprite(string region) {
    $gui.close<Sprite>(region);
  }

  void OverlayUI::show_text(string region, wstring content) {
    $gui.show_text(region, content);
  }

  void OverlayUI::close_text(string region) {
    $gui.close<Text>(region);
  }

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