#include "WebsiteGenerator.h"

#include "TomlReader.h"

void WebsiteGenerator::findProject(const std::string& searchPath)
{
    const auto config_path = std::filesystem::path(searchPath) / "config.toml";
    if (std::filesystem::exists(config_path))
    {
        mProjectPath = searchPath;
        std::cout << "Found config.toml in " << searchPath << std::endl;
    }
}

Path WebsiteGenerator::getConfigPath() const
{
    return mProjectPath / "config.toml";
}

void WebsiteGenerator::readConfig()
{
    auto reader = TomlReader();
    reader.read(getConfigPath());

    if (auto theme_table = reader.getContent()->getTable("themes"))
    {
        auto items = theme_table->getKeyValuePairs();
        auto location = items["location"];
        auto active_theme = items["active_theme"];

        mConfig.setThemePath(location);
        mConfig.setActiveTheme(active_theme);
    }
}

void WebsiteGenerator::parseContentFiles()
{
    findContentFiles();

    for (auto& page : mPages)
    {
        page.load();
    }
}

void WebsiteGenerator::parseTemplateFiles()
{
    const auto template_path = mProjectPath / mConfig.getThemePath() / mConfig.getActiveTheme();

    const auto template_files = Directory::getFilesWithExtension(template_path, ".html");
    for (const auto& path : template_files)
    {
        mTemplateFiles[path.stem().string()] = std::make_unique<TemplateFile>(path);
    }
}

void WebsiteGenerator::doSubstitutions()
{

}

void WebsiteGenerator::write()
{
    // Setup output dir
    const auto output_dir = mProjectPath / "output_custom";
    std::filesystem::create_directory(output_dir);

    // Write each page
}

void WebsiteGenerator::findContentFiles()
{
    const auto pages_files = Directory::getFilesWithExtension(getPagesPath(), ".md");
    for (const auto& path : pages_files)
    {
        mPages.push_back(ContentPage(path));
    }

    const auto article_files = Directory::getFilesWithExtension(getArticlesPath(), ".md");
    for (const auto& path : article_files)
    {
        mArticles.push_back(ContentArticle(path));
    }
}

Path WebsiteGenerator::getContentPath() const
{
    return mProjectPath / "content";
}

Path WebsiteGenerator::getPagesPath() const
{
    return getContentPath() / "pages";
}

Path WebsiteGenerator::getArticlesPath() const
{
    return getContentPath() / "articles";
}
