#pragma once
#include <Logger.h>

#include <string_view>

#include <glm/vec4.hpp>
#include <stb_truetype.h>

namespace glm {
    struct vec4;
}

class TextRenderer
{
private:

    using Vector4f = glm::vec4;
    using BakedChar = stbtt_bakedchar;
    using BakedCharBuffer = std::vector<BakedChar>;
    using ByteBuffer = std::vector<unsigned char>;
    using AlignedQuad = stbtt_aligned_quad;
    static Logger logger;

    int bitmapWidth = 512;
    int bitmapHeight = 512;
    int firstChar = 32;
    int charCount = 96;

    BakedCharBuffer asciiCharData;
    BakedCharBuffer chineseCharData;
    int asciiTextureId = 0;
    int chineseTextureId = 0;

    bool initialized = false;

    // 中文字符起始编码（选择一个不冲突的范围）
    static int CHINESE_FIRST_CHAR; // CJK Unified Ideographs 常用汉字起始范围
    static int CHINESE_CHAR_COUNT;

public:
    TextRenderer(int bitmapWidth, int bitmapHeight, int firstChar, int charCount);
    void initialize(ByteBuffer, float);
    bool isInitialized() const;


    float getTextWidth(std::string text, float scale) const;
    /**
     * 获取一行文字的宽度（单位：像素）
     */
    float getTextWidth(std::string text) const {
        return getTextWidth(text, 1.0f);
    }


    /**
     * 渲染文字
     */
    void renderText(std::string text, float x, float y, Vector4f color, float scale);
    void renderText(std::string text, float x, float y, Vector4f color) {
        renderText(text, x, y, color, 1.0f);
    }

    int createTextureFromBitmap(int width, int height, ByteBuffer pixels);

    void cleanup();

    bool isInitialized() const {
        return initialized;
    }

    int getAsciiTextureId() const {
        return asciiTextureId;
    }

    int getChineseTextureId() const {
        return chineseTextureId;
    }

};

