#include "ContentFile.h"

#include "PathUtils.h"
#include "StringUtils.h"

#include "MarkdownDocument.h"
#include "MarkdownElement.h"
#include "MarkdownComponents.h"

ContentFile::ContentFile(const Path& filename)
    : mFilename(filename)
{

}

ContentFile::~ContentFile()
{

}

Path ContentFile::getFilename() const
{
    return mFilename;
}

std::string ContentFile::getOutputLocation() const
{
    const auto metadata_item = getMetadataItem("save_as");
    return metadata_item.empty() ? PathUtils::getBaseFilename(mFilename) : metadata_item;
}

void ContentFile::load()
{
    MarkdownContentParser parser;
    auto result = parser.run(mFilename);

    mMetadata = result.first;
    mContentBody = std::move(result.second);
}

void ContentFile::doLinkTagSubstitution(const Path& basePath)
{
    auto links = mContentBody->getAllLinks();
    for (const auto link : links)
    {
        auto target = link->getTarget();
        auto replaced_target = StringUtils::removeUpTo(target, "{filename}");
        if (replaced_target != target)
        {
            auto full_path = mFilename.parent_path() / Path(replaced_target);
            auto base_relative_path = PathUtils::getRelativePath(full_path, basePath);
            auto output_path = PathUtils::getPathDelimited(base_relative_path);
            link->setTarget(Path(output_path).replace_extension(".html"));
        }
    }
}

std::string ContentFile::getMetadataItem(const std::string& key) const
{
    const auto check = mMetadata.find(key);
    if (check == mMetadata.end())
    {
        return {};
    }
    else
    {
        return check->second;
    }
}

void ContentFile::write(const Path& path)
{
    File file(path);
    file.writeText(mProcessedOutput);
}
