#include "Label.h"

#include "TextNode.h"
#include "TransformNode.h"
#include "GeometryNode.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, middle);
        mTextNode->setWidth(mSize.mWidth);
        mTextNode->setHeight(mSize.mHeight);
        mRootNode->addChild(mTextNode.get());
    }

    if (mMaterialDirty)
    {
        mTextNode->setFillColor(mBackgroundColor);
    }

    if (mTransformDirty)
    {
        mTextNode->setLocation(middle);
        mTextNode->setWidth(mSize.mWidth);
        mTextNode->setHeight(mSize.mHeight);
    }

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

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