#include "parent_relation_defs.h"

namespace maps {
namespace wiki {

void
ParentRelationDefs::parseParents(const maps::xml3::Node& categoryNode,
                                  const std::string& parentNodeName,
                                  MapParentsByCategory& target)
{
    maps::xml3::Node parent = categoryNode.firstElementChild(parentNodeName);
    const std::string categoryId = categoryNode.attr<std::string>("id");
    while (!parent.isNull()) {
        target.insert(
            std::make_pair(categoryId,
            Parent
            {
                parent.attr<std::string>("category-id"),
                parent.attr<std::string>("role-id"),
                parent.attr<std::string>("type") == "master" 
                    ? RelationType::Master
                    : RelationType::Slave
            }
        ));
        parent = parent.nextElementSibling(parentNodeName);
    }
}

ParentRelationDefs::ParentRelationDefs(const maps::xml3::Node& node)
{
    maps::xml3::Node categoryNode = node.firstElementChild("category");
    while (!categoryNode.isNull()) {
        parseParents(categoryNode, "parent", parentDefinitions_);
        categoryNode = categoryNode.nextElementSibling("category");
    }
}

boost::optional<const ParentRelationDefs::Parent&>
ParentRelationDefs::parentDefinition(const std::string& categoryId) const
{
    auto it = parentDefinitions_.find(categoryId);
    return it != parentDefinitions_.end() 
        ? it->second
        : boost::optional<const ParentRelationDefs::Parent&>();
}

}//wiki
}//maps
