/******************************************************************************
*	File		-	index_buffer.h
*	Author		-	Joey Pollack
*	Date		-	2022/08/05 (y/m/d)
*	Mod Date	-	2022/08/05 (y/m/d)
*	Description	-	OpenGL index buffer object
******************************************************************************/

#include "index_buffer.h"
#include <utils/logger.h>

#include <glad/gl.h>

namespace lunarium
{
    IndexBuffer::IndexBuffer(u32 size, u32* indices)
        : mIsStatic(true), mGLID(0), mIndex(0), mSize(size)
    {
        mIsStatic = indices != nullptr;
        glGenBuffers(1, &mGLID);
        Bind();

        if (indices)
        {
            glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, indices, GL_STATIC_DRAW);
        }
        else
        {
            glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, nullptr, GL_DYNAMIC_DRAW);
        }
    }
    
    // IndexBuffer::IndexBuffer(u32 size)
    //     : mIsStatic(false), mGLID(0), mIndex(0), mSize(size
    // {
    //     glGenBuffers(1, &mGLID);
    //     Bind();
    //     glBufferData(GL_ELEMENT_ARRAY_BUFFER, 0, nullptr, GL_DYNAMIC_DRAW);

    // }
    

    bool IndexBuffer::IsStatic() const
    {
        return mIsStatic;
    }
    
    void IndexBuffer::Clear()
    {
        if (mIsStatic)
        {
            Logger::Warn(LogCategory::GRAPHICS, "Attemping to clear a static VertexBuffer");
        }
        
        mIndex = 0;
    }

    void IndexBuffer::Bind()
    {
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mGLID);
    }
    

    bool IndexBuffer::PushIndices(const u32* indices, u32 size)
    {
        if (mIsStatic)
        {
            Logger::Warn(LogCategory::GRAPHICS, "Cannot push indices into a static buffer!");
            return false;
        }

        // NOTE: BE CAREFUL! mSize is the size in bytes, not number of vertices.
        if (mIndex + size > mSize)
        {
            // Vertices do not fit into the buffer
            Logger::Warn(LogCategory::GRAPHICS, "Cannot push indices into buffer - not enough space left! Space left: %n, data size: %n", mSize - mIndex, size);
            return false;
        }

        Bind();
		glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, mIndex, size, indices);

        mIndex += size;
        return true;
    }

    u32 IndexBuffer::GetGLID() const
    {
        return mGLID;
    }
}