#include "Salamander.h"
#include "Node.h"

namespace Salamander
{

Node::Node() : 
	parent_(NULL)
{
	children_.clear();
}

Node::~Node()
{
	// Delete any children still attached to this node
	while(children_.size())
	{
		Node* child = getChild(0);
		removeChild(0);
		delete child;
		child = NULL;
	}

	// Remove ourselves cleanly from the scene graph
	if(parent_)
	{
		parent_->removeChild(*this);
	}
}

void Node::frame()
{
	// Update all children
	for(std::vector<Node*>::iterator child = children_.begin(); child != children_.end(); ++child)
	{
		(*child)->frame();
	}
}

void Node::assemble()
{

}

bool Node::addChild(Node& child)
{
	// Return false if the child exists
	if(std::find(children_.begin(), children_.end(), &child) != children_.end())
	{
		return false;
	}

	children_.push_back(&child);
	return child.onAdded(*this);
}

bool Node::onAdded(Node& parent)
{
	parent_ = &parent;
	return true;
}

Node* Node::getChild(unsigned int index) const
{
	if(index >= children_.size())
	{
		return NULL;
	}

	return children_[index];
}

unsigned int Node::getChildCount() const
{
	return children_.size();
}

bool Node::removeChild(unsigned int index)
{
	if(index >= children_.size())
	{
		return false;
	}

	// Remove the child from the scene graph
	bool success = children_[index]->onRemoved(*this);
	children_.erase(children_.begin() + index);
	return success;
}

bool Node::removeChild(Node& child)
{
	// Return false if the child does not exist
	std::vector<Node*>::iterator index = std::find(children_.begin(), children_.end(), &child);
	if(index == children_.end())
		return false;

	// Remove the child from the scene graph
	children_.erase(index);
	return child.onRemoved(*this);
}

bool Node::onRemoved(Node& parent)
{
	parent_ = NULL;
	return true;
}

Node* Node::getParent() const
{
	return parent_;
}

}
