#include <GL/glew.h>
#include "../render.h"
#include "manager.h"
#include "../core/buffer/vertexArray.h"
#include "../core/buffer/vertexBuffer.h"
#include "../core/texture/texture.h"
#include "../shader.h"

namespace render::text{

const uint32_t guiBufferSize = 0xfff;

render::vertexArray textVAO;
render::vertexBuffer textVBO;
render::shader textShader;

void init()
{
    textVAO.gen();
    textVBO.gen();

    textVBO.createEmptyBuffer(guiBufferSize*sizeof(textVert), GL_STREAM_DRAW);

    textVAO.bind();
    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    glEnableVertexAttribArray(2);
    textVBO.bind();
    glVertexAttribPointer(0, 2, GL_FLOAT, 0, sizeof(textVert), (GLuint*)(offsetof(textVert, vert)));
    glVertexAttribPointer(1, 2, GL_FLOAT, 0, sizeof(textVert), (GLuint*)(offsetof(textVert, uv)));
    glVertexAttribPointer(2, 4, GL_FLOAT, 0, sizeof(textVert), (GLuint*)(offsetof(textVert, color)));
    textVAO.unbind();
    textVBO.unbind();

    textShader.load("data/shaders/text.xml");
}

void free()
{
    textVAO.free();
    textVBO.free();
    textShader.free();
}

void text(const textVert *data, float scale, uint32_t count, const render::texture *tex)
{
    render::flush();
    render::lock();
    tex->bind(0);
    textShader.bind();
    textShader["scale"] = scale;

    textVBO.subData(count, data);
    textVAO.draw(GL_TRIANGLES, 0, count);
    render::unlock();
}

}
