#include <gearlib.h>
#include <opengl.h>

bool gl_initialized = false;

void init_gl(int major, int minor) {
    if(!glfwInit()) {
        printf("[GLFW] Failed to initialize\n");
        exit(-1);
    } else {
        printf("[GLFW] Initialized successfully\n");
    }

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, major);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minor);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    printf("[OPENGL] Using OpenGL %d.%d\n", major, minor);

    gl_initialized = true;
}

Window create_window(int width, int height, const char* title) {
    if(!gl_initialized) init_gl(4, 6);

    Window window = glfwCreateWindow(width, height, title, NULL, NULL);
    if(!window) {
        printf("[GLFW] Failed to create window\n");
        glfwTerminate();
        exit(-1);
    } else {
        printf("[GLFW] Window created successfully\n");
    }
    glfwMakeContextCurrent(window);
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); 

    if (!gladLoadGL((GLADloadfunc)glfwGetProcAddress)) {
        printf("[GLAD] Failed to initialize\n");
        exit(-1);
    } else {
        printf("[GLAD] Initialized successfully\n");
    }

    glViewport(0, 0, width, height);

    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);  

    return window;
}