#include "guecs/sfml/components.hpp"
#include "guecs/ui.hpp"
#include <fmt/xchar.h>
#include <deque>
#include <iostream>
#include <nlohmann/json.hpp>
#include "dbc.hpp"
#include <memory>
#include "constants.hpp"
#include "slides.hpp"

using std::string, std::wstring, std::shared_ptr, std::make_shared;
using nlohmann::json;

Slide::Slide(const string& title, const string& content, json& config) :
    $title(guecs::to_wstring(title)),
    $content(guecs::to_wstring(content)),
    $config(config)
{
}

void Slide::init(lel::Cell& cell) {
  if(!$initialized) {
    $initialized = true;

    $gui.position(cell.x, cell.y, cell.w, cell.h);
    $gui.layout(
        "[=*%(300,200)title|_|_]"
        "[_|_|_]"
        "[=*%(300,300)content|_|_]"
        "[_|_|_]"
        "[_|_|_]");

    auto title = $gui.entity("title");
    $gui.set<guecs::Text>(title, {$title, TITLE_SIZE});

    auto content = $gui.entity("content");
    $gui.set<guecs::Text>(content, {
        $content,
        CONTENT_SIZE,
        guecs::THEME.TEXT_COLOR, 20});

    $gui.init();
  }
}

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

SlidesUI::SlidesUI(shared_ptr<SlideDeck> slides) {
  dbc::check(slides != nullptr, "slides is null");
  dbc::check(slides->size() > 0, "slide deck is empy");
  $slides = slides;
  $current = 0;

  $gui.position(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
  $gui.layout(
      "[t_left|t_center|t_right]"
      "[m_left|*%(300,400)slide|_|_|m_right]"
      "[_|_|_|_|_]"
      "[_|_|_|_|_]"
      "[_|_|_|_|_]"
      "[_|_|_|_|_]"
      "[b_left|b_center|b_right]"
  );
}

void SlidesUI::init() {
  guecs::Background bg{$gui.$parser, };
  bg.set_color(guecs::THEME.BG_COLOR_DARK);
  $gui.set<guecs::Background>($gui.MAIN, bg);

  show_slide();

  $gui.init();
}

Slide& SlidesUI::current() {
  return $slides->at($current);
}

void SlidesUI::next_slide() {
  if($current < $slides->size() - 1) {
    $current++;
    show_slide();
  }
}

void SlidesUI::prev_slide() {
  if($current > 0) {
    $current--;
    show_slide();
  }
}

void SlidesUI::show_slide() {
  auto& slide = current();
  auto& bg = $gui.get<guecs::Background>($gui.MAIN);
  sf::Color color = guecs::THEME.FILL_COLOR;

  if(slide.$config.contains("bg_color")) {
    auto color_conf = slide.$config["bg_color"];
    color = {color_conf[0], color_conf[1], color_conf[2], color_conf[3]};
  }

  bg.set_color(color);
  bg.init();

  auto& cell = $gui.cell_for("slide");
  slide.init(cell);
}

void SlidesUI::render(sf::RenderWindow& window) {
  $gui.render(window);
  auto& slide = current();
  slide.render(window);

  // $gui.debug_layout(window);
}

void SlidesUI::mouse(float x, float y, guecs::Modifiers mods) {
  $gui.mouse(x, y, mods);

  if(mods.test(guecs::ModBit::left)) {
    next_slide();
  } else if(mods.test(guecs::ModBit::right)) {
    prev_slide();
  }
}
