#include <Encyclopedia/Encyclopedia.hpp>
#include <EncyclopediaCategory/EncyclopediaArticle/EncyclopediaArticle.hpp>
#include <sstream>

Encyclopedia encyclopedia;

void Encyclopedia::init()
{
    registerCategory<EncyclopediaArticle>("articles");
}

const std::string* Encyclopedia::tryGetPage(const std::string &url)
{
    auto cachedPageIt = pageCache.find(url);
    if (cachedPageIt != pageCache.end())
    {
        return &cachedPageIt->second;
    }

    auto slashPos = url.find('/');
    if (slashPos == url.npos)
    {
        return nullptr;
    }

    std::string categoryName = url.substr(0, slashPos);
    std::string pageName = url.substr(slashPos + 1);

    auto categoryIt = categories.find(categoryName);
    if (categoryIt == categories.end())
    {
        return nullptr;
    }

    std::stringstream ss;
    if (!categoryIt->second->tryLoadPage(pageName, ss))
    {
        return nullptr;
    }

    std::string &cached = pageCache[url];
    cached = ss.str();
    return &cached;
}