#include "RectangleNode.h"

#include "Rectangle.h"

#include "MeshPrimitives.h"

#include <iostream>

RectangleNode::RectangleNode(const DiscretePoint& loc, unsigned width, unsigned height)
    : GeometryNode(loc),
      mWidth(width),
      mHeight(height)
{

}

std::unique_ptr<RectangleNode> RectangleNode::Create(const DiscretePoint& loc, unsigned width, unsigned height)
{
    return std::make_unique<RectangleNode>(loc, width, height);
}

GeometryNode::Type RectangleNode::getType()
{
    return GeometryNode::Type::Rectangle;
}

SceneItem* RectangleNode::getSceneItem(std::size_t idx) const
{
    if (idx == 0)
    {
        return mBackgroundItem.get();
    }
    else
    {
        return nullptr;
    }
}

unsigned RectangleNode::getNumSceneItems() const
{
    return 1;
}

unsigned RectangleNode::getWidth() const
{
    return mWidth;
}

unsigned RectangleNode::getHeight() const
{
    return mHeight;
}

void RectangleNode::setWidth(unsigned width)
{
    if (mWidth != width)
    {
        mTransformIsDirty = true;
        mWidth = width;
    }
}

void RectangleNode::setHeight(unsigned height)
{
    if (mHeight != height)
    {
        mTransformIsDirty = true;
        mHeight = height;
    }
}

void RectangleNode::update(FontsManager* fontsManager)
{
    if (!mBackgroundItem || mGeometryIsDirty)
    {
        auto mesh = MeshPrimitives::buildRectangleAsTriMesh();

        if (!mBackgroundItem)
        {
            mBackgroundItem = std::make_unique<SceneModel>(std::move(mesh));
            mBackgroundItem->setName(mName + "_Model");
        }
        else
        {
            mBackgroundItem->updateMesh(std::move(mesh));
        }
        mGeometryIsDirty = false;
    }

    if (mTransformIsDirty)
    {
        mBackgroundItem->updateTransform({mLocation, static_cast<double>(mWidth), static_cast<double>(mHeight)});
        mTransformIsDirty = false;
    }

    if (mMaterialIsDirty)
    {
        mBackgroundItem->updateUniformColor(mFillColor);
        mMaterialIsDirty = false;
    }
}
