#include "config.h"

#include <maps/libs/log8/include/log8.h>
#include <maps/libs/xml/include/xml.h>

#include <filesystem>

namespace maps::wiki::renderer {

namespace fs = std::filesystem;

/*
*Config implementation
*/
Config::Config(const std::string& filename)
{
    INFO() << "USING CONFIG: " << filename;

    maps::xml3::Doc doc(filename);
    layersPath_ = doc.node("/renderer/mapsfolder").value<std::string>();
    defaultLayerName_ = doc.node("/renderer/deflayer").value<std::string>();

    for (fs::directory_iterator itr(layersPath_), end_itr; itr != end_itr; ++itr) {
        if (!fs::is_directory(itr->status())) {
            continue;
        }
        auto filepath = itr->path();
        auto filename = filepath.filename().string();
        if (filename.find('.') != 0) { // skip ".", ".."
            INFO() << "insert layer with path: " << filepath.string();
            layers_.insert({filename, Layer{filename,filepath}});
        }
    }

    REQUIRE(!layers_.empty(), "Layers not found");
    if (!layers_.count(defaultLayerName_)) {
        std::string newDefaultLayerName = layers_.begin()->first;
        WARN() << "deflayer changed to " << newDefaultLayerName <<
            " (was: " << defaultLayerName_ << ")";
        defaultLayerName_ = newDefaultLayerName;
    }
}

} // namespace maps::wiki::renderer

