#include "XmlWriter.h"


std::string XmlWriter::ToString(XmlElement* element, unsigned depth)
{
    const auto prefix = std::string(2*depth, ' ');

    auto content = prefix + "<" + element->GetTagName();
    for (std::size_t idx=0; idx< element->GetNumAttributes(); idx++)
    {
        auto attribute = element->GetAttribute(idx);
        content += " " + attribute->GetName() + "=\"" + attribute->GetValue() + "\"";
    }

    const auto num_children = element->GetNumChildren();
    if (num_children == 0 && element->GetText().empty())
    {
        content += "/>\n";
        return content;
    }
    else
    {
        content += ">";
    }

    if (!element->GetText().empty())
    {
        content += element->GetText();
    }

    if (num_children>0)
    {
        content += "\n";
    }
    for (std::size_t idx=0; idx< element->GetNumChildren(); idx++)
    {
        auto child = element->GetChild(idx);
        content += ToString(child, depth+1);
    }
    if (num_children>0)
    {
        content += prefix;
    }

    content += "</" + element->GetTagName() + ">\n";
    return content;
}

std::string XmlWriter::ToString(XmlDocument* document)
{
    std::string content;
    if (auto prolog = document->GetProlog())
    {
        content += "<?xml";
        for (std::size_t idx=0; idx< prolog->GetNumAttributes(); idx++)
        {
            auto attribute = prolog->GetAttribute(idx);
            content += " " + attribute->GetName() + "=\"" + attribute->GetValue() + "\"";
        }
        content += "?>\n";
    }

    if (auto root = document->GetRoot())
    {
        content += ToString(root);
    }
    return content;
}
