#include "Graphics/Renderable.h"
#include "AssetManager/ModelImporter.h"
#include "PerfCounter.h"


Renderable* Renderable::Load(std::string& path)
{
    return new Renderable(path);
}

Renderable::Renderable(std::string& path)
{
    meshes = ModelImporter::Import(path);

    transform.Scale = glm::vec3(1.0f);
    transform.Rotation = glm::vec3(0.0f, 0.0f, 0.0f);
    transform.Position = glm::vec3(0.0f, 0.0f, 0.0f);

    VAO.Create();
    VAO.Bind();


    vertexBuffer.createBuffer();
    vertexBuffer.Bind(false);
    vertexBuffer.setBufferData(&meshes[0].vertices[0], meshes[0].vertices.size() * sizeof(BarinkEngine::Vertex), false);   

    elementBuffer.createBuffer();
    elementBuffer.Bind(true);
    elementBuffer.setBufferData(&meshes[0].elements[0], meshes[0].elements.size() * sizeof(unsigned int), true);

    VAO.AttachAttribute(0, 3, sizeof(BarinkEngine::Vertex));

   glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(BarinkEngine::Vertex),(void* )offsetof(BarinkEngine::Vertex, vertices));
   glEnableVertexAttribArray(1);
    
   vertexBuffer.Unbind(false);
  
   VAO.Unbind();


}

Renderable::~Renderable()
{
    glDeleteBuffers(1, &UV_id);
}

void Renderable::Draw()
{
    VAO.Bind();
    elementBuffer.Bind(true);

    glActiveTexture(GL_TEXTURE0);
    glUniform1i(glGetUniformLocation(shader->id, "Texture"), GL_TEXTURE0);
    texture->Bind();

    ES->verts = meshes[0].vertices.size();
    ES->DC++;
    glDrawElements(GL_TRIANGLES, static_cast<unsigned int>(meshes[0].elements.size()), GL_UNSIGNED_INT, NULL);
    VAO.Unbind();

}
