#include "client/rendering/FontRenderer.h"

FontRenderer::FontRenderer() : buffer(8 * 1024 * 1024), tex("resources/font8x8.png") {
    vertexBuffer.bind();
    vertexBuffer.setFloatAttribute(0, 2, 0, 7);
    vertexBuffer.setFloatAttribute(1, 2, 2, 7);
    vertexBuffer.setFloatAttribute(2, 3, 4, 7);
}

void FontRenderer::drawString(float x, float y, const char* text) {
    vertexBuffer.bind();

    const int maxIndex = 256;
    buffer.reset(maxIndex * 4 * sizeof (float) * 7);

    int index = 0;
    float r = 1.0f;
    float g = 1.0f;
    float b = 1.0f;

    while(text[index] != '\0' && index < maxIndex) {
        char c = text[index];
        if(c == '&') {
            if(text[index + 1] == '\0' || text[index + 2] == '\0' || text[index + 3] == '\0') {
                break;
            }
            r = (text[index + 1] - '0') * (1.0f / 9.0f);
            g = (text[index + 2] - '0') * (1.0f / 9.0f);
            b = (text[index + 3] - '0') * (1.0f / 9.0f);
            index += 4;
            continue;
        }

        float minX = (c & 0xF) * (1.0f / 16.0f) + 1.0f / 128.0f;
        float minY = (c >> 4) * (1.0f / 16.0f);
        float maxX = minX + (1.0f / 16.0f) - 2.0f / 128.0f;
        float maxY = minY + (1.0f / 16.0f);

        buffer.add(x).add(y).add(minX).add(minY).add(r).add(g).add(b);
        buffer.add(x).add(y + 8).add(minX).add(maxY).add(r).add(g).add(b);
        buffer.add(x + 6).add(y).add(maxX).add(minY).add(r).add(g).add(b);
        buffer.add(x + 6).add(y + 8).add(maxX).add(maxY).add(r).add(g).add(b);

        x += 6;
        index++;
    }
    
    tex.bind(0);
    buffer.draw(7);
}