#include "Mesh.h"
#include <cstring>
#include <iostream>

using namespace std;

Mesh::Mesh()
{
    data = new float[dataSize * 7];
}

Mesh::Mesh(const Mesh& orig)
{
}

Mesh::~Mesh()
{
    delete[] data;
    glDeleteVertexArrays(1, &vba);
    glDeleteBuffers(1, &vbo);
}

void Mesh::init()
{
    glGenVertexArrays(1, &vba);
    glBindVertexArray(vba);
    
    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);

    glVertexAttribPointer(0, 3, GL_FLOAT, 0, 28, (GLvoid*) 0);
    glEnableVertexAttribArray(0);

    glVertexAttribPointer(1, 4, GL_FLOAT, 0, 28, (GLvoid*) 12);
    glEnableVertexAttribArray(1);       
}

void Mesh::addPoint(float x, float y, float z, float r, float g, float b, float a)
{
    if(vertices >= dataSize)
    {
        float* newData = new float[dataSize * 2 * 7];
        memcpy(newData, data, sizeof(float) * dataSize * 7);
        delete[] data;
        data = newData;
        dataSize *= 2;
    }
    unsigned int index = vertices * 7;
    data[index] = x;
    data[index + 1] = y;
    data[index + 2] = z;
    data[index + 3] = r;
    data[index + 4] = g;
    data[index + 5] = b;
    data[index + 6] = a;
    
    vertices++;
}

void Mesh::build()
{
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
   
    /*for(int i = 0; i < vertices; i++)
    {
        int index = i * 7;
        cout << data[index] << " " << data[index + 1] << " " << data[index + 2] 
                << " " << data[index + 3] << " " << data[index + 4]  << " " 
                << data[index + 5] << " " << data[index + 6] << endl;
    }*/
    
    glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 7 * vertices, data, GL_STATIC_DRAW);
}

void Mesh::draw()
{
    glBindVertexArray(vba);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glDrawArrays(GL_TRIANGLES, 0, vertices);
}