#pragma once

#include <cstdint>

#include "log.h"
#include "renderer_gl/opengl_capabilities.h"

namespace pp::legacy::gl_renderbuffer {

inline void gen_opengl_renderbuffers(std::uint32_t count, std::uint32_t* ids) noexcept
{
    glGenRenderbuffers(static_cast<GLsizei>(count), reinterpret_cast<GLuint*>(ids));
}

inline void delete_opengl_renderbuffers(std::uint32_t count, const std::uint32_t* ids) noexcept
{
    glDeleteRenderbuffers(static_cast<GLsizei>(count), reinterpret_cast<const GLuint*>(ids));
}

inline void bind_opengl_renderbuffer(std::uint32_t target, std::uint32_t renderbuffer) noexcept
{
    glBindRenderbuffer(static_cast<GLenum>(target), static_cast<GLuint>(renderbuffer));
}

inline void set_opengl_renderbuffer_storage(
    std::uint32_t target,
    std::uint32_t internal_format,
    std::int32_t width,
    std::int32_t height) noexcept
{
    glRenderbufferStorage(
        static_cast<GLenum>(target),
        static_cast<GLenum>(internal_format),
        static_cast<GLsizei>(width),
        static_cast<GLsizei>(height));
}

inline void attach_opengl_framebuffer_renderbuffer(
    std::uint32_t target,
    std::uint32_t attachment,
    std::uint32_t renderbuffer_target,
    std::uint32_t renderbuffer) noexcept
{
    glFramebufferRenderbuffer(
        static_cast<GLenum>(target),
        static_cast<GLenum>(attachment),
        static_cast<GLenum>(renderbuffer_target),
        static_cast<GLuint>(renderbuffer));
}

inline std::uint32_t allocate_depth_renderbuffer(std::int32_t width, std::int32_t height, const char* context)
{
    const auto result = pp::renderer::gl::allocate_opengl_depth_renderbuffer(
        width,
        height,
        pp::renderer::gl::OpenGlDepthRenderbufferAllocationDispatch {
            .gen_renderbuffers = gen_opengl_renderbuffers,
            .bind_renderbuffer = bind_opengl_renderbuffer,
            .renderbuffer_storage = set_opengl_renderbuffer_storage,
        });
    if (!result.ok()) {
        LOG("%s failed because: %s", context, result.status().message);
        return 0U;
    }
    return result.value();
}

inline void attach_depth_renderbuffer(std::uint32_t renderbuffer, const char* context)
{
    const auto status = pp::renderer::gl::attach_opengl_depth_renderbuffer(
        renderbuffer,
        pp::renderer::gl::OpenGlDepthRenderbufferAttachmentDispatch {
            .framebuffer_renderbuffer = attach_opengl_framebuffer_renderbuffer,
        });
    if (!status.ok())
        LOG("%s failed because: %s", context, status.message);
}

inline void delete_renderbuffer(std::uint32_t renderbuffer, const char* context)
{
    const auto status = pp::renderer::gl::delete_opengl_renderbuffer(
        renderbuffer,
        pp::renderer::gl::OpenGlRenderbufferDeleteDispatch {
            .delete_renderbuffers = delete_opengl_renderbuffers,
        });
    if (!status.ok())
        LOG("%s failed because: %s", context, status.message);
}

} // namespace pp::legacy::gl_renderbuffer
