#include "ritual_ui.hpp"
#include "components.hpp"
#include "guecs.hpp"
#include "rand.hpp"
#include "animation.hpp"
#include "rand.hpp"
#include "sound.hpp"

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

  RitualUI::RitualUI(GameLevel level) :
    $level(level)
  {
    $gui.position(STATUS_UI_X, STATUS_UI_Y, STATUS_UI_WIDTH, STATUS_UI_HEIGHT);
    $gui.layout(
        "[_]"
        "[inv_slot0 | inv_slot1 | inv_slot2| inv_slot3]"
        "[inv_slot4 | inv_slot5 | inv_slot6| inv_slot7]"
        "[inv_slot8 | inv_slot9 | inv_slot10| inv_slot11]"
        "[inv_slot12 | inv_slot13 | inv_slot14| inv_slot15]"
        "[*%(100,600)circle_area]"
        "[_]"
        "[_]"
        "[_]"
        "[_]"
        "[_]"
        "[ ritual_ui ]");
  }

  void RitualUI::init() {
    auto& blanket = $level.world->get_the<ritual::Blanket>();
    int i = 0;

    blanket.contents.query<ritual::JunkItem>([&](const auto, auto& item) {
      std::string slot = fmt::format("inv_slot{}", i++);
      std::string sprite_name = fmt::format("{}-64", item);

      auto button = $gui.entity(slot);
      $gui.set<Sprite>(button, {sprite_name});
      $gui.set<Effect>(button, {0.4f});
      $gui.set<Sound>(button, {"ui_click"});
      $gui.set<Clickable>(button, {
          [&](auto ent, auto){ inv_slot_clicked(ent); }
      });
    });

    auto circle = $gui.entity("circle_area");
    $gui.set<Effect>(circle, {0.4f});
    $gui.set<Sprite>(circle, {"the_ritual_circle"});
    $gui.set<Clickable>(circle, {
        [&](auto ent, auto){ ritual_circle_clicked(ent); }
    });

    auto open_close_toggle = $gui.entity("ritual_ui");
    $gui.set<Clickable>(open_close_toggle, {[&](auto, auto){ toggle(); }});
    $gui.set<Sound>(open_close_toggle, {"pickup"});

    $ritual_ui = textures::get("ritual_crafting_area");
    $ritual_ui.sprite->setPosition({0,0});
    $ritual_ui.sprite->setTextureRect($ritual_closed_rect);
    $ritual_state = RitualUIState::CLOSED;
    $ritual_anim = animation::load("ritual_blanket");

    $gui.init();
  }

  bool RitualUI::is_open() {
    return $ritual_state != RitualUIState::CLOSED;
  }

  void RitualUI::inv_slot_clicked(DinkyECS::Entity ent) {
    if($gui.has<Sprite>(ent)) {
      auto& bs = $gui.get<Sprite>(ent);
      auto ritual_circle = $gui.entity("circle_area");
      auto& ritual_cell = $gui.cell_for(ritual_circle);
      dbc::log(fmt::format("inv_slot clicked {}", bs.name));

      int inner_x = ritual_cell.x + ritual_cell.x / 2;
      int inner_y = ritual_cell.y + ritual_cell.y / 2;

      float x = Random::uniform(inner_x, inner_x + ritual_cell.w / 2);
      float y = Random::uniform(inner_y, inner_y + ritual_cell.h / 2);
      bs.sprite->setPosition({float(x), float(y)});
    }

    $engine.set_state($blanket, "has_magick", true);
  }

  void RitualUI::reset_inv_positions() {
    auto ritual_circle = $gui.entity("circle_area");

    $gui.world().query<lel::Cell, Sprite>(
      [&](const auto ent, auto &cell, auto &bs) {
        if(ent == ritual_circle) {
          bs.sprite->setColor({255,255,255,255});
          bs.sprite->setRotation(sf::degrees(0.0));
        } else {
          bs.sprite->setPosition({(float)cell.x, (float)cell.y});
        }
    });
  }

  void RitualUI::ritual_circle_clicked(DinkyECS::Entity ent) {
    auto cell = $gui.cell_for(ent);
    auto& bs = $gui.get<Sprite>(ent);
    bs.sprite->setColor({200, 0, 0});
    animation::center(*bs.sprite, {(float)cell.x, (float)cell.y});
    animation::rotate(*bs.sprite, 20.0);

    // finalize here ritual here
    $engine.plan($blanket);

    if($blanket.is_combined()) {
      // add it to the belt
      auto ritual = $engine.finalize($blanket);
      auto& the_belt = $level.world->get_the<ritual::Belt>();
      the_belt.equip(0, ritual);
      $level.world->send<Events::GUI>(Events::GUI::NEW_RITUAL, $level.player, {});
      reset_inv_positions();
    } else {
      fmt::println("Failed to combine!");
      sound::play("ui_click");
    }
  }

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

  void RitualUI::toggle() {
    using enum RitualUIState;

    if($ritual_state == OPEN) {
      $ritual_state = CLOSING;
    } else if($ritual_state == CLOSED) {
      $blanket = $engine.start();
      $ritual_state = OPENING;
      $ritual_anim.play();
    }
  }

  /* WARNING: This is really not the greatest way to do this.
   * look in status_ui.update_level()
   * */
  void RitualUI::update() {
    dbc::log("RITUAL UPDATE NOT IMPLEMENTED");
  }

  void RitualUI::render(sf::RenderWindow &window) {
    using enum RitualUIState;

    if($ritual_state == OPENING) {
      if(!animation::apply($ritual_anim, $ritual_ui)) {
        $ritual_state = OPEN;
      }
    } else if($ritual_state == CLOSING) {
      reset_inv_positions();
      $ritual_ui.sprite->setTextureRect($ritual_closed_rect);
      $ritual_state = CLOSED;
    }

    window.draw(*$ritual_ui.sprite);
    if($ritual_state == OPEN) $gui.render(window);
  }
}
