#include "pch.h"
#include "app.h"
#include "renderer_api/shader_catalog.h"
#include "renderer_gl/opengl_capabilities.h"
#include "shader.h"

namespace {

[[nodiscard]] GLenum extension_count_query() noexcept
{
    return static_cast<GLenum>(pp::renderer::gl::extension_count_query());
}

[[nodiscard]] GLenum extension_string_name() noexcept
{
    return static_cast<GLenum>(pp::renderer::gl::extension_string_name());
}

}

void App::initShaders()
{
#ifdef _DEBUG
    if (!check_uniform_uniqueness())
        LOG("check_uniform_uniqueness() failed");
#endif // _DEBUG

    render_task([] {
        GLint n_exts;
        glGetIntegerv(extension_count_query(), &n_exts);
        std::vector<std::string> extension_storage;
        std::vector<std::string_view> extension_views;
        extension_storage.reserve(n_exts);
        extension_views.reserve(n_exts);
        for (int i = 0; i < n_exts; i++)
        {
            extension_storage.emplace_back((const char*)glGetStringi(extension_string_name(), i));
            extension_views.push_back(extension_storage.back());
            LOG("EXT: %s", extension_storage.back().c_str());
        }

        pp::renderer::gl::OpenGlRuntime runtime;
#if __GL__
        runtime.desktop_gl = true;
#endif
#if __GLES__
        runtime.gles = true;
#endif
#if __WEB__
        runtime.web = true;
#endif
        const auto capabilities = pp::renderer::gl::detect_opengl_capabilities(extension_views, runtime);
        ShaderManager::ext_framebuffer_fetch = capabilities.framebuffer_fetch;
        ShaderManager::ext_map_aligned = capabilities.map_buffer_alignment;
        ShaderManager::ext_float32 = capabilities.float32_textures;
        ShaderManager::ext_float32_linear = capabilities.float32_linear;
        ShaderManager::ext_float16 = capabilities.float16_textures;
    });
    
#if __GL__
    // In OpenGL 3.3 these should be already available
    ShaderManager::ext_float32_linear = true;
    ShaderManager::ext_float32 = true;
    ShaderManager::ext_float16 = true;
#endif

    LOG("Shader Extension shader_framebuffer_fetch: %s", ShaderManager::ext_framebuffer_fetch ? "enabled" : "disabled");

    LOG("initializing shaders");
    const auto shader_catalog = pp::renderer::panopainter_shader_catalog();
    const auto catalog_status = pp::renderer::validate_shader_catalog(shader_catalog);
    if (!catalog_status.ok())
    {
        LOG("Shader catalog validation failed: %s", catalog_status.message);
        return;
    }

    for (const auto& shader : shader_catalog)
    {
        if (!ShaderManager::load(static_cast<kShader>(const_hash(shader.name)), shader.path))
            LOG("Failed to create shader %s", shader.name);
    }
    LOG("shaders initialized");
}


