#include "engine/opengl.hpp"

// OpenGLContext Constructor
OpenGLContext::OpenGLContext(SDLWindow& window): window(window), lastTime(SDL_GetTicks()), frameTime(0.0f) {
    glContext = SDL_GL_CreateContext(window.getSDLWindow());
    if (!glContext) {
        // Handle context creation error
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to create OpenGL context: %s", SDL_GetError());
        return;
    }
    SDL_GL_MakeCurrent(window.getSDLWindow(), glContext);
}

// OpenGLContext Destructor
OpenGLContext::~OpenGLContext() {
    if (glContext) {
        SDL_GL_DestroyContext(glContext);
    }
}

// Check if Initialized
bool OpenGLContext::isInitialized() const {
    return glContext != nullptr;
}

// Make Context Current
void OpenGLContext::makeCurrent() {
    SDL_GL_MakeCurrent(window.getSDLWindow(), glContext);
}

// Swap Buffers
void OpenGLContext::swapBuffers() {
    SDL_GL_SwapWindow(window.getSDLWindow());

    // Update frame time
    Uint32 currentTime = SDL_GetTicks();
    frameTime = (currentTime - lastTime) / 1000.0f;
    lastTime = currentTime;
}

// Get Frame Time
float OpenGLContext::getFrameTime() {
    return frameTime;
}