#include "graphicalcontainernode.h"
#include "scenetree.h"

GraphicalContainerNode::~GraphicalContainerNode()
{
    setSceneTree(nullptr);
    for(GraphicalNode* child : m_children)
        delete child;
}

void GraphicalContainerNode::update()
{
    if(m_transformChanged)
        m_combinedTransform = m_transform * m_parentTransform;
    for(GraphicalNode* child : m_children)
    {
        if(m_transformChanged)
            child->setParentTransform(m_combinedTransform);
        child->update();
    }
}

void GraphicalContainerNode::setSceneTree(SceneTree* tree)
{
    SceneNode::setSceneTree(tree);
    for(GraphicalNode* child : m_children)
        child->setSceneTree(tree);
}

void GraphicalContainerNode::addChild(GraphicalNode *node)
{
    if(node != nullptr)
    {
        if(m_scene != nullptr)
            node->setSceneTree(m_scene);
        m_children.push_back(node);
        node->m_parent = this;
        node->setParentTransform(m_transform);
        node->setParentVisible(isVisible());
    }
}

void GraphicalContainerNode::removeChild(GraphicalNode *node)
{
    if(node != nullptr)
    {
        for(auto it = m_children.begin(); it != m_children.end();)
        {
            if(*it == node)
            {
                it = m_children.erase(it);
                node->m_parent = nullptr;
                node->setSceneTree(nullptr);
            }
            else
                ++it;
        }
    }
}

void GraphicalContainerNode::updateVisibility(bool visible)
{
    for(GraphicalNode* child : m_children)
        child->setParentVisible(visible);
}
