#include "TemplatingEngine.h"

#include "Directory.h"

#include <iostream>

TemplatingEngine::TemplatingEngine(const Path& workingDirectory)
	: mWorkingDirectory(workingDirectory)
{

}

void TemplatingEngine::loadTemplateFiles()
{
	const auto files = Directory::getFilesWithExtension(mWorkingDirectory, mTemplateExtension);
	for (const auto& file : files)
	{
		mTemplateFiles.push_back(std::make_unique<TemplateFile>(file));
	}
}

std::string TemplatingEngine::processTemplate(const std::string& name)
{
	if (auto file = getTemplateFile(name))
	{
		return processTemplate(file);
	}
	return {};
}

TemplateFile* TemplatingEngine::getTemplateFile(const Path& path)
{
	return getTemplateFile(path.stem().string());
}

TemplateFile* TemplatingEngine::getTemplateFile(const std::string& name)
{
	std::cout << "Looking for template file with name: " << name << std::endl;
	for (const auto& file : mTemplateFiles)
	{
		if (file->getName() == name)
		{
			return file.get();
		}
	}
	return nullptr;
}

std::string TemplatingEngine::processTemplate(TemplateFile* file, TemplateNode* parent)
{
	file->loadContent();
	file->dumpContent();

	auto content = file->getContent();
	if (parent)
	{
		content->setExtensionParent(parent);
	}

	if (auto extension_node = content->getFirstChildShallow<TemplateExtends>())
	{
		std::cout << "Found extension node" << std::endl;
		if (auto extension_template = getTemplateFile(Path(extension_node->getPath())))
		{
			std::cout << "Found extension template" << std::endl;
			return processTemplate(extension_template, parent);
		}
		else
		{
			return render(content);
		}
	}
	else
	{
		return render(content);
	}
}

std::string TemplatingEngine::render(TemplateNode* content)
{
	return content->render();
}