#include "TemplateNode.h"

#include "TemplateSubstitutionContext.h"

TemplateNode::TemplateNode(TemplateNode* parent)
        : mParent(parent)
{

}

TemplateNode* TemplateNode::getParent() const
{
    return mParent;
}

void TemplateNode::addChild(std::unique_ptr<TemplateNode> child)
{
    mChildren.push_back(std::move(child));
}

std::size_t TemplateNode::getNumChildren() const
{
    return mChildren.size();
}

TemplateNode* TemplateNode::getFirstChildShallow(Type type, const std::string& identifier) const
{
    for (const auto& child : mChildren)
    {
        if (child->getType() == type)
        {
            if (!identifier.empty())
            {
                if (child->getIdentifier() == identifier)
                {
                    return child.get();
                }
            }
            else
            {
                return child.get();
            }
        }
    }
    return nullptr;
}

TemplateNode::Type TemplateNode::getType() const
{
    return Type::NONE;
}

std::string TemplateNode::getIdentifier() const
{
    return {};
}

TemplateNode* TemplateNode::getChild(std::size_t index) const
{
    return mChildren[index].get();
}

std::string TemplateNode::getRawContent() const
{
    std::string content;
    for (const auto& child : mChildren)
    {
        content += child->getRawContent() + "\n";
    }
    return content;
}

void TemplateNode::setExtensionParent(TemplateNode* parent)
{
    mExtensionParent = parent;
}

void TemplateNode::setExtensionBase(TemplateNode* base)
{
    mExtensionBase = base;
}

std::string TemplateNode::render(TemplateSubstitutionContext* substitutions, TemplateNode* parentContext)
{
    if (mExtensionBase)
    {
        return mExtensionBase->render(substitutions, this);
    }

    if (!parentContext && mExtensionParent)
    {
        parentContext = mExtensionParent;
    }

    std::string content;
    for (size_t idx = 0; idx < mChildren.size(); idx++)
    {
        content += mChildren[idx]->render(substitutions, parentContext);
    }
    return content;
}
