#include <asset/asset.h>
#include <input/input.h>
#include <log/log.h>
#include <transform/transform.h>
#include <window/window.h>

#include <GLFW/glfw3.h>
#include <flecs.h>
#include <iostream>

int main()
{
    Log::initialize();

    flecs::world world;

    world.import <Window::WindowModule>();
    world.import <Input::InputModule>();
    world.import <Asset::AssetModule>();
    world.import <TransformModule>();

#ifndef NDEBUG
    world.import <flecs::stats>();
    world.set<flecs::Rest>({});
#endif

    world.system<Window::Window, Input::ButtonInput<Input::KeyCode> const>("CatchMouse")
        .each([](flecs::entity e,
                 Window::Window,
                 Input::ButtonInput<Input::KeyCode> const& button_input) {
            if (button_input.just_pressed(Input::KeyCode(GLFW_KEY_LEFT_CONTROL))) {
                auto glfw_window = e.get<std::shared_ptr<GLFWwindow>>();
                auto input_mode = glfwGetInputMode(glfw_window->get(), GLFW_CURSOR);

                if (input_mode == GLFW_CURSOR_NORMAL) {
                    glfwSetInputMode(glfw_window->get(), GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
                } else {
                    glfwSetInputMode(glfw_window->get(), GLFW_CURSOR, GLFW_CURSOR_NORMAL);
                }
            }
        });

    world.system<Window::Window, Input::ButtonInput<Input::KeyCode> const>("CloseOnEsc")
        .each([](flecs::entity e,
                 Window::Window,
                 Input::ButtonInput<Input::KeyCode> const& button_input) {
            if (button_input.just_pressed(Input::KeyCode(GLFW_KEY_ESCAPE))) {
                e.world().quit();
            }
        });

    world.system("PollEvents").kind(flecs::PreUpdate).run([](flecs::iter&) { glfwPollEvents(); });

    world.system<std::shared_ptr<GLFWwindow>>("Render")
        .kind(flecs::PostUpdate)
        .each([](std::shared_ptr<GLFWwindow>& glfw_window) { glfwSwapBuffers(glfw_window.get()); });

    auto parent = world.entity("TestParent").add<Transform>().add<GlobalTransform>();
    parent.get_mut<Transform>()->translation += glm::vec3(1.0);

    auto child = world.entity("TestChild").add<Transform>().add<GlobalTransform>();
    child.get_mut<Transform>()->translation += glm::vec3(1.0);
    child.child_of(parent);

    while (world.progress()) {
    }
}
