#pragma once

#include <cstdint>

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

namespace pp::legacy::gl_pixel_buffer {

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

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

inline void bind_opengl_buffer(std::uint32_t target, std::uint32_t buffer) noexcept
{
    glBindBuffer(static_cast<GLenum>(target), static_cast<GLuint>(buffer));
}

inline void set_opengl_buffer_data(
    std::uint32_t target,
    std::intptr_t byte_count,
    const void* data,
    std::uint32_t usage) noexcept
{
    glBufferData(
        static_cast<GLenum>(target),
        static_cast<GLsizeiptr>(byte_count),
        data,
        static_cast<GLenum>(usage));
}

inline void* map_opengl_buffer_range(
    std::uint32_t target,
    std::intptr_t offset,
    std::intptr_t byte_count,
    std::uint32_t access) noexcept
{
    return glMapBufferRange(
        static_cast<GLenum>(target),
        static_cast<GLintptr>(offset),
        static_cast<GLsizeiptr>(byte_count),
        static_cast<GLbitfield>(access));
}

inline void unmap_opengl_buffer(std::uint32_t target) noexcept
{
    glUnmapBuffer(static_cast<GLenum>(target));
}

inline pp::renderer::gl::OpenGlPixelBufferAllocationDispatch pixel_buffer_allocation_dispatch() noexcept
{
    return pp::renderer::gl::OpenGlPixelBufferAllocationDispatch {
        .gen_buffers = gen_opengl_buffers,
    };
}

inline pp::renderer::gl::OpenGlPixelBufferReadbackDispatch pixel_buffer_readback_dispatch() noexcept
{
    return pp::renderer::gl::OpenGlPixelBufferReadbackDispatch {
        .gen_buffers = gen_opengl_buffers,
        .bind_buffer = bind_opengl_buffer,
        .buffer_data = set_opengl_buffer_data,
        .read_pixels = pp::legacy::gl_framebuffer::read_opengl_pixels,
    };
}

inline pp::renderer::gl::OpenGlPixelBufferMapDispatch pixel_buffer_map_dispatch() noexcept
{
    return pp::renderer::gl::OpenGlPixelBufferMapDispatch {
        .bind_buffer = bind_opengl_buffer,
        .map_buffer_range = map_opengl_buffer_range,
    };
}

inline pp::renderer::gl::OpenGlPixelBufferUnmapDispatch pixel_buffer_unmap_dispatch() noexcept
{
    return pp::renderer::gl::OpenGlPixelBufferUnmapDispatch {
        .bind_buffer = bind_opengl_buffer,
        .unmap_buffer = unmap_opengl_buffer,
    };
}

inline pp::renderer::gl::OpenGlPixelBufferDeleteDispatch pixel_buffer_delete_dispatch() noexcept
{
    return pp::renderer::gl::OpenGlPixelBufferDeleteDispatch {
        .delete_buffers = delete_opengl_buffers,
    };
}

} // namespace pp::legacy::gl_pixel_buffer
