#include "render/indexbuffer.h"
#include "render/gl_shared.h"

IndexBuffer::IndexBuffer(void* data, size_t size, bool isStream /*= false*/)
{
	glGenBuffers(1, &m_buffer);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_buffer);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, data, isStream ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

	//if (isStream) {
	//	Logger::msg("created dynamic index stream ...");
	//}
}

IndexBuffer::~IndexBuffer()
{
	glDeleteBuffers(1, &m_buffer);
}

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

void* IndexBuffer::MapBuffer(BufferAccess access)
{
	GLenum accessGl = 0;

	switch (access)
	{
	case BufferAccess::READ_ONLY:
		accessGl = GL_READ_ONLY;
		break;
	case BufferAccess::WRITE_ONLY:
		accessGl = GL_WRITE_ONLY;
		break;
	case BufferAccess::READ_WRITE:
		accessGl = GL_READ_WRITE;
		break;
	}

	Bind();

	void* ptr = glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, accessGl);

	//check_for_opengl_error();

	return ptr;
}

void IndexBuffer::UnmapBuffer()
{
	Bind();
	glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);
}
