#include "gui/fsm.hpp"
#include "graphics/textures.hpp"
#include "game/sound.hpp"
#include "ai/ai.hpp"
#include <iostream>
#include "graphics/shaders.hpp"
#include "gui/backend.hpp"
#include "game/level.hpp"
#include "graphics/camera.hpp"
#include "game/systems.hpp"

int main(int argc, char* argv[]) {
  try {
    gui::Backend backend;

    shaders::init();
    components::init();
    guecs::init(&backend);
    ai::init("ai");
    GameDB::init();
    cinematic::init();
    sound::mute(true);

    gui::FSM main;
    System::init(main.$systems);
    main.event(game::Event::START);

    sound::play("ambient_1", true);

    while(main.active()) {
      main.update();
      main.render();

      // BUG: need to sort out how to deal with this in the FSM
      if(main.in_state(gui::State::IDLE)
          || main.in_state(gui::State::START_SCREEN)
          || main.in_state(gui::State::LOOTING))
      {
        main.handle_keyboard_mouse();
      } else{
        main.event(game::Event::TICK);
      }

      main.handle_world_events();
    }

    return 0;
  } catch(const std::system_error& e) {
    std::cout << "WARNING: On OSX you'll get this error on shutdown.\n";
    std::cout << "Caught system_error with code "
                 "[" << e.code() << "] meaning "
                 "[" << e.what() << "]\n";
  }
}
