#include "MeshNode.h"

#include <iostream>

MeshNode::MeshNode(const DiscretePoint& location)
 : MaterialNode(location)
{

}

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

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

void MeshNode::setMesh(AbstractMesh* mesh)
{
    mWorkingMesh = mesh;
    mMeshIsDirty = true;
}

SceneItem* MeshNode::getSceneItem(std::size_t idx) const
{
    return mModel.get();
}

unsigned MeshNode::getNumSceneItems() const
{
    if (mWorkingMesh)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

void MeshNode::update(FontsManager* fontsManager)
{
    if (!mModel || mMeshIsDirty)
    {
        if (!mModel)
        {
            mModel = std::make_unique<SceneModel>(nullptr);
            mModel->setName(mName + "_MeshModel");
            mModel->setShowOutline(true);
        }

        if (mWorkingMesh)
        {
            mModel->updateMesh(mWorkingMesh);
            mMeshIsDirty = false;
        }
    }

    if (mWorkingMesh && mMeshIsDirty)
    {
        std::cout << "Updating mesh with " << mWorkingMesh->getNumNodes() << std::endl;
        mModel->updateMesh(mWorkingMesh);
        mMeshIsDirty = false;
    }

    if (mTransformIsDirty)
    {
        auto size = mHeight > mWidth ? mWidth : mHeight;
        mModel->updateTransform({mLocation, static_cast<double>(size), static_cast<double>(size)});
        mTransformIsDirty = false;
    }

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

