#include "GLExt.h"
#include "Logger.h"

#ifdef _WIN32
#   include <Windows.h>
#endif

namespace UsdLayerManager {
namespace GL {

#ifdef _WIN32
// wglGetProcAddress only resolves extension / ARB functions.
// Core functions (OpenGL 1.x) live in opengl32.dll and must be
// fetched via GetProcAddress.  This two-stage loader covers both.
static GLADapiproc WinGLLoader(const char* name) {
    GLADapiproc proc = reinterpret_cast<GLADapiproc>(wglGetProcAddress(name));
    if (!proc) {
        HMODULE hMod = GetModuleHandleA("opengl32.dll");
        if (hMod) {
            proc = reinterpret_cast<GLADapiproc>(GetProcAddress(hMod, name));
        }
    }
    return proc;
}
#endif

bool InitExtensions() {
    // Must be called after wglMakeCurrent so the context is current.
#ifdef _WIN32
    int version = gladLoadGL(WinGLLoader);
#else
    int version = 0; // supply a platform loader for non-Windows
#endif

    if (version == 0) {
        LOG_ERROR("gladLoadGL failed - could not load OpenGL functions");
        return false;
    }

    LOG_INFO("OpenGL loaded via glad (GL "
             + std::to_string(GLAD_VERSION_MAJOR(version)) + "."
             + std::to_string(GLAD_VERSION_MINOR(version)) + ")");
    return true;
}

} // namespace GL
} // namespace UsdLayerManager
