#include "spriteRenderer.h"


SpriteRenderer::SpriteRenderer(Shader& shader)
{
    this->shader = shader;
    this->initRenderData();
}

SpriteRenderer::~SpriteRenderer()
{
    glDeleteVertexArrays(1, &this->quadVAO);
}

void SpriteRenderer::DrawSprite(Texture& texture, glm::vec2 position, glm::vec4 UV, glm::vec2 size, GLfloat rotate)
{
    GLfloat vertices[] = {
        // Pos      // Tex
        0.0f, 1.0f,  UV.x, UV.y,
        1.0f, 0.0f,  UV.z, UV.w,
        0.0f, 0.0f,  UV.x, UV.w,
        1.0f, 1.0f,  UV.z, UV.y
    };
    ResourceManager::GetShader("shader").Use();
    glm::mat4 model = glm::mat4(1.0);
    model = glm::translate(model, glm::vec3(position, 0.0f)); // First translate
    model = glm::scale(model, glm::vec3(size, 0.0f));    // Last scale

    ResourceManager::GetShader("shader").SetMatrix4("model", model);

    glBindBuffer(GL_ARRAY_BUFFER, this->VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    // Prepare transformations
    //this->shader.Use();
    //glm::mat4 model = glm::mat4(1.0);
    
   // model = glm::translate(model, glm::vec3(position, 0.0f));  // First translate (transformations are: scale happens first, then rotation and then finall translation happens; reversed order)

    //model = glm::translate(model, glm::vec3(0.5f * size.x, 0.5f * size.y, 0.0f)); // Move origin of rotation to center of quad
    //model = glm::rotate(model, rotate, glm::vec3(0.0f, 0.0f, 1.0f)); // Then rotate
    //model = glm::translate(model, glm::vec3(-0.5f * size.x, -0.5f * size.y, 0.0f)); // Move origin back

    //model = glm::scale(model, glm::vec3(size, 1.0f)); // Last scale
    
    //this->shader.SetMatrix4("model", model);
    
    // Render textured quad

    texture.bind(); 

    glBindVertexArray(this->quadVAO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->EBO);
    glDrawElements(
        GL_TRIANGLES,      // mode
        6,    // count
        GL_UNSIGNED_INT,   // type
        (void*)0           // element array buffer offset
    );
}

void SpriteRenderer::initRenderData()
{
    // Configure VAO/VBO
    unsigned int indices[] = {
        2, 1, 0,
        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);
}   