#include "config.h"

#include <maps/libs/log8/include/log8.h>
#include <yandex/maps/wiki/common/extended_xml_doc.h>
#include <util/system/env.h>
#include <util/string/strip.h>

namespace maps::wiki::renderer_overlay {

namespace {
const std::string LOG_LEVEL_CONFIG_LOCATION = "/renderer-overlay/log/level";
const std::string DEFAULT_LOG_LEVEL = "info";

std::unique_ptr<Config> s_cfg_;
} // namespace

std::string getEnvString(const std::string& name)
{
    auto token = Strip(GetEnv(name.c_str()));
    return token;
}

Config::Config(const std::string& filename, const std::string& servicesCfgFileName)
    : servicesConfigXml_(servicesCfgFileName)
    , aclPool_(servicesConfigXml_, "core", "editor")
    , viewTrunkPool_(servicesConfigXml_, "view-trunk", "editor")
    , viewStablePool_(servicesConfigXml_, "view-stable", "editor")
{
    maps::wiki::common::ExtendedXmlDoc doc(filename);
    s3EndPoint_ = doc.get<std::string>("/renderer-overlay/s3mds/end-point");
    s3Bucket_ = doc.get<std::string>("/renderer-overlay/s3mds/bucket");
    s3SourceImagesFolder_ = doc.get<std::string>("/renderer-overlay/s3mds/sources-path");
    s3AccessKeyId_ = getEnvString("AWS_ACCESS_KEY_ID");
    s3AccessKeySecret_ = getEnvString("AWS_SECRET_ACCESS_KEY");
    if (s3AccessKeyId_.empty()) {
        s3AccessKeyId_= doc.get<std::string>("/renderer-overlay/s3mds/key");
    }
    if (s3AccessKeySecret_.empty()) {
        s3AccessKeySecret_ = doc.get<std::string>("/renderer-overlay/s3mds/secret");
    }
    logLevel_ = doc.get<std::string>("/renderer-overlay/log/level");
}

pgpool3::Pool&
Config::viewPool(revision::DBID branchId) const
{
    return branchId == revision::TRUNK_BRANCH_ID
        ? viewTrunkPool_.pool()
        : viewStablePool_.pool();
}

ConfigScope::ConfigScope(const std::string& fileName, const std::string& servicesCfgFileName)
{
    s_cfg_.reset(new Config(fileName, servicesCfgFileName));
}
ConfigScope::~ConfigScope()
{
    s_cfg_.reset();
}

Config* cfg()
{
    ASSERT(s_cfg_);
    return s_cfg_.get();
}

} // namespace maps::wiki::renderer_overlay
