#include "font.h"
#include <SparrowRenderer/pbrmaterial.h>
#include "SparrowRenderer/mesh.h"
#include "scene/textnode.h"

Font::Font()
{

}

TextNode* Font::getTextNode(std::string s, glm::vec3 color, float font_size,bool visible)
{
    if(s.empty()) return nullptr;

    std::wstring ws;
    ws.assign(s.begin(),s.end());
    Mesh* textmesh =  new Mesh();
    glm::vec2 dimension(0,m_defaultLineHeight);
    glm::vec2 current_pos(0.f);
    float sizeRatio = font_size / m_defaultLineHeight;
    for(wchar_t c : ws){
        if(c == '\n')
        {
            current_pos.x = 0.f; // left alignment -> TODO : be able to center or align right
            current_pos.y += m_defaultLineHeight;
            if (dimension.x < current_pos.x)
                dimension.x = current_pos.x;
            dimension.y += m_defaultLineHeight;
        }
        else
        {
            CharInfo charInfo = m_charTable[c];
            textmesh->addRectangle2D((current_pos + charInfo.offset)* sizeRatio,
                                     charInfo.dim * sizeRatio,
                                     charInfo.pos * m_scale,
                                     charInfo.dim * m_scale
                                     );
            current_pos.x += charInfo.xadvance;
        }
    }
    PBRMaterial *mat = new PBRMaterial();
    // TODO : delete this material somewhere (garbage collector ?)
    mat->setTexture(PBRMaterial::ALPHA_SLOT, m_tex, "font_texture");
    mat->albedo = color;
    textmesh->setMaterial((Material*)mat);
    textmesh->initGL();
    TextNode *text = new TextNode(textmesh,ws,font_size,visible);
    if (dimension.x < current_pos.x)
        dimension.x = current_pos.x;
    text->setDimension(dimension * sizeRatio);
    return text;
}
