#include "xml_utility.h"

#include <sdpxml/sdpxml.h>

namespace k3d
{

namespace xml
{

sdpxml::Element& safe_element(sdpxml::Element& Parent, const std::string& Name)
{
	return safe_element(Parent, sdpxml::Element(Name));
}

sdpxml::Element& safe_element(sdpxml::Element& Parent, const sdpxml::Element& Search)
{
	return safe_element(Parent, Search, Search);
}

sdpxml::Element& safe_element(sdpxml::Element& Parent, const sdpxml::Element& Search, const sdpxml::Element& Prototype)
{
	for(sdpxml::ElementCollection::iterator child = Parent.Children().begin(); child != Parent.Children().end(); ++child)
		{
			if(child->Name() != Search.Name())
				continue;
				
			sdpxml::AttributeCollection::const_iterator search_attribute;
			for(search_attribute = Search.Attributes().begin(); search_attribute != Search.Attributes().end(); ++search_attribute)
				{
					sdpxml::AttributePointer attribute = sdpxml::FindAttribute(*child, sdpxml::SameName(search_attribute->Name()));
					if(!attribute)
						break;

					if(attribute->Value() != search_attribute->Value())
						break;
				}
				
			if(search_attribute != Search.Attributes().end())
				continue;
				
			return *child;
		}

	return Parent.Append(Prototype);
}

} // namespace xml

} // namespace k3d

