#include "MeshNode.h"

#include "SceneModel.h"
#include "AbstractMesh.h"

MeshNode::MeshNode(const Transform& transform)
 : MaterialNode(transform)
{

}

MeshNode::~MeshNode()
{

}

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

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

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

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

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

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

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

    if (mWorkingMesh && mMeshIsDirty)
    {
        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->updateSolidMaterial(*mMaterial);
        mMaterialIsDirty = false;
    }
}

