#include "window_manager.h"

#include <spdlog/spdlog.h>

#include "renderer_window.h"
#include "core/renderer/renderer.h"

void on_window_size_change(GLFWwindow* changed_window, int width, int height) {
    aorii::s_window_manager->on_glfw_window_size_callback(changed_window, width, height);
}

window_manager::~window_manager() {
    for (const auto window : windows) {
        aorii::get_renderer_raw()->destroy_window(window);
    }
    windows.clear();
}

renderer_window* window_manager::create_window(const Eigen::Vector2i& in_size, const std::string& in_title) {
    const auto window = aorii::get_renderer_raw()->create_window();
    if (!window->init(in_size, in_title)) {
        delete window;
        spdlog::error("Failed to create window");
        return nullptr;
    }
    const auto glfw_window = window->get_glfw_window();
    glfwSetFramebufferSizeCallback(glfw_window, on_window_size_change);
    windows.push_back(window);
    return window;
}

void window_manager::on_glfw_window_size_callback(GLFWwindow* in_window, int width, int height) {
    auto find = find_window(in_window);
    if (!find) return;
    find->on_resize({ width, height });
}

renderer_window* window_manager::find_window(GLFWwindow* in_window) {
    auto it = std::find_if(windows.begin(), windows.end(), [in_window](renderer_window* w) {
        return w->get_glfw_window() == in_window;
    });
    if (it != windows.end()) { return *it; }
    return nullptr;
}
