#include "guecs.hpp"
#include "shaders.hpp"

namespace guecs {

  void Textual::init(lel::Cell &cell, shared_ptr<sf::Font> font_ptr) {
    dbc::check(font_ptr != nullptr, "you failed to initialize this WideText");
    if(font == nullptr) font = font_ptr;
    if(text == nullptr) text = make_shared<sf::Text>(*font, content, size);
    text->setFillColor(color);

    if(centered) {
      auto bounds = text->getLocalBounds();
      auto text_cell = lel::center(bounds.size.x, bounds.size.y, cell);
      // this stupid / 2 is because SFML renders from baseline rather than from the claimed bounding box
      text->setPosition({float(text_cell.x), float(text_cell.y) - text_cell.h / 2});
    } else {
      text->setPosition({float(cell.x + padding * 2), float(cell.y + padding * 2)});
    }

    text->setCharacterSize(size);
  }

  void Textual::update(std::wstring& new_content) {
    content = new_content;
    text->setString(content);
  }

  void Sprite::init(lel::Cell &cell) {
    auto sprite_texture = textures::get(name);

    sprite = make_shared<sf::Sprite>(
        *sprite_texture.texture,
        sprite_texture.sprite->getTextureRect());

    sprite->setPosition({
        float(cell.x + padding),
        float(cell.y + padding)});

    auto bounds = sprite->getLocalBounds();

    sprite->setScale({
        float(cell.w - padding * 2) / bounds.size.x,
        float(cell.h - padding * 2) / bounds.size.y});
  }

  void Rectangle::init(lel::Cell& cell) {
    sf::Vector2f size{float(cell.w) - padding * 2, float(cell.h) - padding * 2};
    if(shape == nullptr) shape = make_shared<sf::RectangleShape>(size);
    shape->setPosition({float(cell.x + padding), float(cell.y + padding)});
    shape->setFillColor(color);
    shape->setOutlineColor(border_color);
    shape->setOutlineThickness(border_px);
  }


  void Meter::init(lel::Cell& cell) {
    bar.init(cell);
  }


  void Background::init() {
    sf::Vector2f size{float(w), float(h)};
    if(shape == nullptr) shape = make_shared<sf::RectangleShape>(size);
    shape->setPosition({float(x), float(y)});
    shape->setFillColor(color);
  }

  void Shader::init(lel::Cell &cell) {
    auto shader = shaders::get(name);
    shader->setUniform("u_resolution", sf::Vector2f({float(cell.w), float(cell.h)}));
    clock = std::make_shared<sf::Clock>();
  }

  void Shader::step() {
    auto shader = shaders::get(name);
    sf::Time u_time = clock->getElapsedTime();
    float current_time = u_time.asSeconds();

    if(current_time < u_time_end) {
      shader->setUniform("u_time", current_time);
    } else {
      active = false;
    }
  }

  void Shader::run() {
    auto shader = shaders::get(name);

    active = true;
    sf::Time u_time = clock->getElapsedTime();
    u_time_end = u_time.asSeconds() + duration;
    shader->setUniform("u_duration", duration);
    shader->setUniform("u_time_end", u_time_end);
  }

  UI::UI() {
    $font = make_shared<sf::Font>(FONT_FILE_NAME);
  }

  void UI::position(int x, int y, int width, int height) {
    $parser.position(x, y, width, height);
  }

  void UI::layout(std::string grid) {
    $grid = grid;
    bool good = $parser.parse($grid);
    dbc::check(good, "LEL parsing failed.");

    for(auto& [name, cell] : $parser.cells) {
      auto ent = init_entity(name);
      $world.set<lel::Cell>(ent, cell);
    }
  }

  DinkyECS::Entity UI::init_entity(std::string name) {
    auto entity = $world.entity();
    // this lets you look up an entity by name
    $name_ents.insert_or_assign(name, entity);
    // this makes it easier to get the name during querying
    $world.set<CellName>(entity, {name});
    return entity;
  }

  DinkyECS::Entity UI::entity(std::string name) {
    dbc::check($name_ents.contains(name),
        fmt::format("GUECS entity {} does not exist. Forgot to init_entity?", name));
    return $name_ents.at(name);
  }

  void UI::init() {
    if($world.has_the<Background>()) {
      auto& bg = $world.get_the<Background>();
      bg.init();
    }

    $world.query<Background>([](auto, auto& bg) {
        bg.init();
    });

    $world.query<lel::Cell, Rectangle>([](auto, auto& cell, auto& rect) {
      rect.init(cell);
    });

    $world.query<lel::Cell, Shader>([](auto, auto& cell, auto& shader) {
        shader.init(cell);
    });

    $world.query<Rectangle, Meter>([](auto, auto& bg, auto &) {
        bg.shape->setFillColor(ColorValue::BLACK);
    });

    $world.query<lel::Cell, Meter>([](auto, auto &cell, auto& meter) {
        meter.init(cell);
    });

    $world.query<lel::Cell, Textual>([this](auto, auto& cell, auto& text) {
      text.init(cell, $font);
    });

    $world.query<lel::Cell, Label>([this](auto, auto& cell, auto& text) {
      text.init(cell, $font);
    });

    $world.query<lel::Cell, Sprite>([&](auto, auto &cell, auto &sprite) {
        sprite.init(cell);
    });
  }

  void UI::debug_layout(sf::RenderWindow& window) {
    $world.query<lel::Cell>([&](const auto, auto &cell) {
        sf::RectangleShape rect{{float(cell.w), float(cell.h)}};
        rect.setPosition({float(cell.x), float(cell.y)});
        rect.setFillColor(sf::Color::Transparent);
        rect.setOutlineColor(sf::Color::Red);
        rect.setOutlineThickness(2.0f);
        window.draw(rect);
    });
  }

  void UI::render(sf::RenderWindow& window) {
    if($world.has_the<Background>()) {
      auto& bg = $world.get_the<Background>();
      window.draw(*bg.shape);
    }

    $world.query<Shader>([&](auto, auto& shader) {
      if(shader.active) shader.step();
    });

    $world.query<Rectangle>([&](auto ent, auto& rect) {
        render_helper(window, ent, true, rect.shape);
    });

    $world.query<lel::Cell, Meter>([&](auto ent, auto& cell, const auto &meter) {
        float level = std::clamp(meter.percent, 0.0f, 1.0f) * float(cell.w);
        // ZED: this 6 is a border width, make it a thing
        meter.bar.shape->setSize({std::max(level, 0.0f), float(cell.h - 6)});
        render_helper(window, ent, true, meter.bar.shape);
    });

    $world.query<Sprite>([&](auto ent, auto& sprite) {
        render_helper(window, ent, false, sprite.sprite);
    });

    $world.query<Label>([&](auto ent, auto& text) {
        render_helper(window, ent, false, text.text);
    });

    $world.query<Textual>([&](auto ent, auto& text) {
        render_helper(window, ent, true, text.text);
    });
  }

  bool UI::mouse(float x, float y) {
    int action_count = 0;

    $world.query<lel::Cell, Clickable>([&](auto ent, auto& cell, auto &clicked) {
      if((x >= cell.x && x <= cell.x + cell.w) &&
          (y >= cell.y && y <= cell.y + cell.h))
      {
        if($world.has<Shader>(ent)) {
          auto& shader = $world.get<Shader>(ent);
          shader.run();
        }

        if(auto action_data = get_if<ActionData>(ent)) {
          clicked.action(ent, action_data->data);
        } else {
          clicked.action(ent, {});
        }

        action_count++;
      }
    });

    return action_count > 0;
  }

  void UI::show_sprite(string region, string sprite_name) {
    auto ent = entity(region);

    if(!has<Sprite>(ent)) {
      Sprite to_show{sprite_name};
      auto& cell = cell_for(ent);
      to_show.init(cell);
      set<guecs::Sprite>(ent, to_show);
    }
  }

  void UI::show_text(string region, wstring content) {
    auto ent = entity(region);

    if(auto text = get_if<Textual>(ent)) {
      text->text->setString(content);
    } else {
      auto &cell = cell_for(ent);
      Textual to_set{content, 20};
      to_set.init(cell, $font);
      to_set.text->setFillColor(ColorValue::LIGHT_MID);
      set<Textual>(ent, to_set);
    }
  }

  void UI::show_label(string region, wstring content) {
    auto ent = entity(region);

    if(auto text = get_if<Label>(ent)) {
      text->text->setString(content);
    } else {
      auto &cell = cell_for(ent);
      Label to_set{content, 20};
      to_set.init(cell, $font);
      to_set.text->setFillColor(ColorValue::LIGHT_MID);
      set<Label>(ent, to_set);
    }
  }

  Clickable make_action(DinkyECS::World& target, Events::GUI event) {
    return {[&, event](auto ent, auto data){
      // remember that ent is passed in from the UI::mouse handler
      target.send<Events::GUI>(event, ent, data);
    }};
  }

}