#include <gearlib.h>
#include <assert.h>

vec3 quad_vertex_positions[6] = {
    { -0.5f, 0.5f, 0.0f },
    { -0.5f, -0.5f, 0.0f },
    { 0.5f, -0.5f, 0.0f },
    
    { -0.5f, 0.5f, 0.0f },
    { 0.5f, -0.5f, 0.0f },
    { 0.5f, 0.5f, 0.0f },
};

RenderBatch* quad_batch = NULL;

void setup_quads() {
    quad_batch = create_quad_batch();
}

void draw_quad(vec2 pos, vec2 size, vec4 color) { 
    mat4 transform = mat4Multiply(
            mat4Scale(size.x, size.y, 1.0f), 
            mat4Translate(pos.x, pos.y, 0.0f));

    draw_quad_trans(transform, color);
}

void draw_quad_trans(mat4 transform, vec4 color) {
    assert(quad_batch != NULL && "quad_batch is null, was setup_quads() called?");

    batch_draw_quad(quad_batch, transform, color);
}

void batch_draw_quad(RenderBatch* batch, mat4 transform, vec4 color) {
    uint32_t vertex_add = 6; 

    if(batch_needs_flush(batch, vertex_add))
        flush_batch(batch);
    
    for(int i = 0; i < vertex_add; i++) {
        QuadVertex* vertex = batch->vertex_ptr;

        vertex->Position = vec3Transform(quad_vertex_positions[i], transform);
        vertex->Color = color;

        batch->vertex_ptr += batch->vertex_size;
        batch->vertex_count++;
    }
}

RenderBatch* create_quad_batch() {
    RenderBatch* quad_batch = create_batch(sizeof(QuadVertex), MAX_VERTICES);
    quad_batch->shader = load_shader_program(
            compile_shader("assets/quad.vert", GL_VERTEX_SHADER),
            compile_shader("assets/quad.frag", GL_FRAGMENT_SHADER), 0);
  
    batch_add_attrib(quad_batch, (VertexAttrib){ 
        .type = GL_FLOAT, .size = sizeof(float), .count = 3 
    }); // pos 
    
    batch_add_attrib(quad_batch, (VertexAttrib){ 
        .type = GL_FLOAT, .size = sizeof(float), .count = 4 
    }); // color

    batch_bind_attribs(quad_batch);
    
    return quad_batch;
}
