#include "client/rendering/FontRenderer.h"
#include "gaming-core/wrapper/Attributes.h"
#include "gaming-core/utils/Buffer.h"

FontRenderer::FontRenderer() : tex("resources/font8x8.png") {
    vertexBuffer.setAttributes(Attributes().addFloat(2).addFloat(2).addColor4());
    vertexBuffer.setStreamData(MAX_CHARS * VERTEX_SIZE * 4);
}

void FontRenderer::drawString(float x, float y, const char* text) {
    Buffer buffer(MAX_CHARS * VERTEX_SIZE * 4);

    int index = 0;
    Color4 color(0xFF, 0xFF, 0xFF, 0xFF);

    while(text[index] != '\0' && index < MAX_CHARS) {
        char32_t c = text[index];
        if(c > 128 && index + 1 < MAX_CHARS && text[index + 1] != '\0') {
            index++;
            c = (text[index] & 0x3F) | ((c & 0x1F) << 6);
        }
        if(c == '&') {
            if(text[index + 1] == '\0' || text[index + 2] == '\0' || text[index + 3] == '\0') {
                break;
            }
            color[0] = ((text[index + 1] - '0') * 255) / 9;
            color[1] = ((text[index + 2] - '0') * 255) / 9;
            color[2] = ((text[index + 3] - '0') * 255) / 9;
            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(color);
        buffer.add(x).add(y + 8).add(minX).add(maxY).add(color);
        buffer.add(x + 6).add(y).add(maxX).add(minY).add(color);
        buffer.add(x + 6).add(y + 8).add(maxX).add(maxY).add(color);

        x += 6;
        index++;
    }

    tex.bindTo(0);
    vertexBuffer.updateData(0, buffer.getLength(), buffer);
    vertexBuffer.drawStrip(buffer.getLength() / VERTEX_SIZE);
}