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

namespace td {
namespace render {

void VertexCache::addData(std::uint64_t index, std::vector<float> positions, std::vector<float> colors) {
    ElementsIndex positionsIndexes;
    positionsIndexes.first = m_Positions.end();
    m_Positions.insert(m_Positions.end(), positions.begin(), positions.end());
    positionsIndexes.second = m_Positions.end() - 1;

    ElementsIndex colorsIndexes;
    colorsIndexes.first = m_Colors.end();
    m_Colors.insert(m_Colors.end(), colors.begin(), colors.end());
    colorsIndexes.second = m_Colors.end() - 1;

    m_Indexes.insert({ index, {positionsIndexes, colorsIndexes} });
}

void VertexCache::removeData(std::uint64_t index) {
    auto it = m_Indexes.find(index);
    if (it != m_Indexes.end()) {
        DataIndex indexes = it->second;
        ElementsIndex positionsIndexes = indexes.first;
        ElementsIndex colorsIndexes = indexes.second;

        m_Positions.erase(positionsIndexes.first, positionsIndexes.second);
        m_Colors.erase(colorsIndexes.first, colorsIndexes.second);

        m_Indexes.erase(it);
    }
}

void VertexCache::clear() {
    m_Positions.clear();
    m_Colors.clear();
    m_Indexes.clear();
}

void VertexCache::updateVertexArray() {
    m_VertexArray = std::make_unique<GL::VertexArray>(m_Colors.size()); // one color per vertex

    GL::VertexBuffer positionsBuffer(m_Positions, 2);
    positionsBuffer.addVertexAttribPointer(0, 2, 0);

    GL::VertexBuffer colorsBuffer(m_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
