#include "Mesh.h"

#include <GL/glew.h>
#include <iostream>

Mesh::Mesh(std::vector<Vertex2D> vertices, std::vector<unsigned int> indices, Texture2D texture)
{
	this->texture = texture;
	this->vertices = vertices;
	this->indices = indices;

	setupMesh();
}

void Mesh::setupMesh()
{
	//Create VAO & Bind
	glGenVertexArrays(1, &VAO);
	glBindVertexArray(VAO);
	//Create VBO
	glGenBuffers(1, &VBO);
	glBindBuffer(GL_ARRAY_BUFFER, VBO);
	glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex2D), &vertices[0], GL_STATIC_DRAW);
	//Create EBO
	glGenBuffers(1, &EBO);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW);

	//Set attriPointer and enable
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), (void *)0);

	glEnableVertexAttribArray(1);
	glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), (void *)offsetof(Vertex2D, texCoord));

	//Cleanup
	glBindVertexArray(0);
}

Mesh::~Mesh()
{
	std::cout << "Deleting Mesh" << std::endl;
	glDeleteBuffers(1, &VBO);
	glDeleteBuffers(1, &EBO);
	glDeleteBuffers(1, &VAO);
}

unsigned int Mesh::getIndicesCount() const
{
	return indices.size();
}

void Mesh::bindVAO() const
{
	glBindVertexArray(this->VAO);
}

void Mesh::bindTexture() const
{
	texture.Bind();
}
