#include "client/render/VertexCache.h"
#include "client/render/loader/GLLoader.h"

namespace td {
namespace render {

const static int VERTEX_SIZE = 3;

void VertexCache::AddData(std::uint64_t index, std::vector<float> positions, std::vector<float> colors) {
	m_Indexes.insert({ index, {positions, colors} });
	m_VertexCount += colors.size(); // one color per vertex
}

void VertexCache::RemoveData(std::uint64_t index) {
	auto it = m_Indexes.find(index);
	if (it != m_Indexes.end()) {
		m_VertexCount -= it->second.color.size(); // one color per vertex
		m_Indexes.erase(it);
	}
}

void VertexCache::Clear() {
	m_Indexes.clear();
	m_VertexCount = 0;
}

void VertexCache::UpdateVertexArray() {
	m_VertexArray = std::make_unique<GL::VertexArray>(m_VertexCount); // one color per vertex

	Vector positions;
	positions.reserve(m_VertexCount * VERTEX_SIZE);

	Vector colors;
	colors.reserve(m_VertexCount);

	for (auto it = m_Indexes.begin(); it != m_Indexes.end(); it++) {
		const DataIndex& data = it->second;

		positions.insert(positions.end(), data.position.begin(), data.position.end());
		colors.insert(colors.end(), data.color.begin(), data.color.end());
	}

	GL::VertexBuffer positionsBuffer(positions, VERTEX_SIZE);
	positionsBuffer.AddVertexAttribPointer(0, VERTEX_SIZE, 0);

	GL::VertexBuffer colorsBuffer(colors, 1);
	colorsBuffer.AddVertexAttribPointer(1, 1, 0);

	m_VertexArray->Bind();
	m_VertexArray->BindVertexBuffer(positionsBuffer);
	m_VertexArray->BindVertexBuffer(colorsBuffer);
	m_VertexArray->Unbind();
}

} // namespace render
} // namespace td
