#include "object.h"

Object::Object(Texture sprite, glm::vec2 pos, glm::vec2 size, int blockType)
	: sprite(sprite), position(pos), size(size), blockType(blockType)
{
	this->spriteUVs = this->spriteSheet->getUVs(this->blockType + 10);
	//if (this->blockType) {
	this->objectBody.min = c2V(this->position.x, this->position.y);
	this->objectBody.max = c2V(this->position.x + this->size.x, this->position.y + this->size.y);
	//}
	GLfloat newVertices[] = {
		// Pos      // Tex
		0.0f * this->size.x + this->position.x, 1.0f * this->size.y + this->position.y, this->spriteUVs.x, this->spriteUVs.y,
		1.0f * this->size.x + this->position.x, 0.0f * this->size.y + this->position.y, this->spriteUVs.z, this->spriteUVs.w,
		0.0f * this->size.x + this->position.x, 0.0f * this->size.y + this->position.y, this->spriteUVs.x, this->spriteUVs.w,
		1.0f * this->size.x + this->position.x, 1.0f * this->size.y + this->position.y, this->spriteUVs.z, this->spriteUVs.y};
	for (int i = 0; i < 16; i++)
	{
		this->vertices[i] = newVertices[i];
	}

	// Configure VAO/VBO
	unsigned int indices[] = {
		0, 1, 2,
		0, 1, 3};

	glGenVertexArrays(1, &this->quadVAO);
	glGenBuffers(1, &this->VBO);
	glGenBuffers(1, &this->EBO);

	glBindBuffer(GL_ARRAY_BUFFER, this->VBO);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->EBO);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

	glBindVertexArray(this->quadVAO);
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid *)0);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindVertexArray(0);
	glActiveTexture(GL_TEXTURE0);
	glBindBuffer(GL_ARRAY_BUFFER, this->VBO);
	glBufferData(GL_ARRAY_BUFFER, sizeof(this->vertices), this->vertices, GL_STATIC_DRAW);
}

void Object::drawObject(SpriteRenderer &renderer)
{
	//renderer.DrawSprite(this->Sprite, this->Position, this->spriteUVs, this->vertices, this->Size, this->Rotation);
	this->sprite.bind();
	glBindVertexArray(this->quadVAO);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->EBO);
	glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
}