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

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

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

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

void VertexBuffer::Bind()
{
	glBindBuffer(GL_ARRAY_BUFFER, m_buffer);
}

void* VertexBuffer::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_ARRAY_BUFFER, accessGl);

	//check_for_opengl_error();

	return ptr;
}

void VertexBuffer::UnmapBuffer()
{
	Bind();
	glUnmapBuffer(GL_ARRAY_BUFFER);
}

void VertexBuffer::UpdateBuffer(void* data, size_t size)
{
	glBufferData(GL_ARRAY_BUFFER, size, data, GL_DYNAMIC_DRAW);
	GL_CHECK_ERROR();
}
