#include "labelnode.h"
#include "tools/font.h"
#include "resourcemanager.h"

#include "SparrowRenderer/mesh.h"
#include "SparrowRenderer/pbrmaterial.h"

#include <iostream>

#define LABEL_TEXT_DEPTH 15

LabelNode::LabelNode():
    m_string(""),
    m_color(glm::vec3(1,1,1))
{
    Font* font = RESOURCE_GET(Font,"shellfont");
    m_text = font->getTextNode(m_string,m_color,32);
    if(m_text){
        m_text->setDepth(LABEL_TEXT_DEPTH);
        addChild(m_text);
    }
}

void LabelNode::setText(std::string s)
{
    m_string = s;
    m_string_updated = true;
}

void LabelNode::setColor(glm::vec3 color){
    m_color= color;
    m_color_updated = true;
}

glm::vec2 LabelNode::getDimension(){
    if(m_text)
        return m_text->getDimension();
    else
        return glm::vec2(0,0);
}

bool LabelNode::wasUpdated(){
    return m_was_updated;
}

void LabelNode::update(){
    GUINode::update();
    if(m_was_updated)
        m_was_updated = false;
    if(m_string_updated){
        if(m_text != nullptr)
        {
            removeChild(m_text);
            delete(m_text);
        }
        Font* font = RESOURCE_GET(Font,"shellfont");
        m_text = font->getTextNode(m_string,m_color,32);
        m_text->setDepth(LABEL_TEXT_DEPTH);
        m_text->getGeometryNode()->mesh->setName("labelText");
        addChild(m_text);
        m_string_updated= false;
        m_color_updated=false;
        m_was_updated=true;
    }
    if(m_color_updated){
        if(m_text){
            PBRMaterial* mat = (PBRMaterial*) m_text->m_geometry.mesh->getMaterial();
            mat->albedo = m_color;
            m_color_updated = false;
        }
    }
}
