#include "Label.h"

#include "TextNode.h"
#include "TransformNode.h"
#include "GeometryNode.h"

#include "ThemeManager.h"
#include "PaintEvent.h"

Label::Label()
    : Widget(),
      mLabel()
{
    mName = "Label";
}

std::unique_ptr<Label> Label::Create()
{
    return std::make_unique<Label>();
}

void Label::setLabel(const std::string& text)
{
    if (text != mLabel)
    {
        mLabel = text;
        mContentDirty = true;
    }
}

bool Label::isDirty() const
{
    return Widget::isDirty() || mContentDirty;
}

void Label::doPaint(const PaintEvent* event)
{
    updateBackground(event);
    updateLabel(event);
}

void Label::updateLabel(const PaintEvent* event)
{
    unsigned fontOffset = unsigned(mLabel.size()) * 4;
    auto middle = DiscretePoint(mLocation.getX() + mSize.mWidth/2 - fontOffset, mLocation.getY() + mSize.mHeight/2 + 4);

    if (!mTextNode)
    {
        mTextNode = TextNode::Create(mLabel, Transform());
        mTextNode->setWidth(mSize.mWidth);
        mTextNode->setHeight(mSize.mHeight);
        mRootNode->addChild(mTextNode.get());
    }

    if (mMaterialDirty)
    {
        mTextNode->setFillColor(event->getThemesManager()->getColor(mBackground));
    }

    if (mContentDirty)
    {
        mTextNode->setContent(mLabel);
        mContentDirty = false;
    }

    if (mVisibilityDirty)
    {
        mTextNode->setIsVisible(mVisible);
    }
}
