#include "guecs/sfml/backend.hpp"
#include "guecs/ui.hpp"
#include <fmt/xchar.h>
#include "dbc.hpp"
#include "constants.hpp"
#include "slides.hpp"
#include "control.hpp"
#include "parser.hpp"

int main(int argc, char *argv[]) {
  dbc::check(argc >= 2, "USAGE: besos my_fucking_slides.md");

  sfml::Backend backend;
  guecs::init(&backend);

  auto& modes = sf::VideoMode::getFullscreenModes();
  auto screen_mode = std::find_if(modes.begin(), modes.end(), [=](const auto& a) -> bool {
      return a.size.x == WINDOW_WIDTH && a.size.y == WINDOW_HEIGHT;
  });

  sf::RenderWindow controller(sf::VideoMode({CONTROL_WIDTH, CONTROL_HEIGHT}), "Besos Loves Control");

  sf::RenderWindow presenter(*screen_mode,
      "Besos Loves Slides", sf::Style::None, sf::State::Windowed);

  presenter.setFramerateLimit(FRAME_LIMIT);
  presenter.setVerticalSyncEnabled(VSYNC);

  auto data = parse_slides(argv[1]);

  SlidesUI slides(data);
  slides.init();

  ControlUI control_ui(presenter);
  control_ui.init();

  dbc::check(control_ui.$status != nullptr, "bad ptr");

  while(controller.isOpen()) {
    while (const auto event = presenter.pollEvent()) {
      if(const auto* mouse = event->getIf<sf::Event::MouseButtonPressed>()) {
        sf::Vector2f pos = presenter.mapPixelToCoords(mouse->position);

        if(mouse->button == sf::Mouse::Button::Left) {
          slides.mouse(pos.x, pos.y, {1 << guecs::ModBit::left});
        } else if(mouse->button == sf::Mouse::Button::Right) {
          slides.mouse(pos.x, pos.y, {1 << guecs::ModBit::right});
        }
      }
    }

    while (const auto event = controller.pollEvent()) {
      if(event) control_ui.handle_events(controller, *event);
    }

    slides.render(presenter);
    control_ui.render(controller);

    presenter.display();
    controller.display();
  }
}
