#include <maps/wikimap/mapspro/services/mrc/drive/firmware_updater/libs/config/include/config.h>

#include <maps/libs/config/include/config.h>
#include <maps/libs/common/include/file_utils.h>

namespace maps::fw_updater::config {

namespace {

const auto CONFIG_TEMPLATE_RESOURCE_KEY = "t-config.xml";
const std::string DB_ID = "core";
const std::string POOL_ID = "core";

} // namespace


S3Config::S3Config(const xml3::Node& node)
    : host_(node.node("client").attr("host"))
    , publicReadHost_(node.node("client").attr("public-read-host", std::string{}))
    , connectTimeoutMs_(node.node("client").attr<size_t>("connect-timeout-ms"))
    , requestTimeoutMs_(node.node("client").attr<size_t>("request-timeout-ms"))
    , bucket_(node.node("bucket").attr("bucket"))
    , accessKeyId_(node.node("bucket").attr("access-key-id"))
    , accessKeySecret_(node.node("bucket").attr("access-key-secret"))
{}

StorageConfig::StorageConfig(const xml3::Node& node)
    : url_(node.attr("url"))
    , cli_(node.node("cli"))
{}

StorageConfig::Cli::Cli(const xml3::Node& node)
    : oauthAppClientId_(node.attr("oauth-app-client-id"))
    , oauthAppClientSecret_(node.attr("oauth-app-client-secret"))
{}

UpdaterConfig::UpdaterConfig(const xml3::Node& node)
    : signatureKey_(node.attr("signature-key"))
{}

Config::Config(const vault_boy::Context& ctx)
    : Config(std::make_shared<xml3::Doc>(
    xml3::Doc::fromString(
        ctx.renderTemplate(
            maps::config::readConfigFile(CONFIG_TEMPLATE_RESOURCE_KEY)))))
{
}

Config::Config(const vault_boy::Context& ctx, const std::string& path)
    : Config(std::make_shared<xml3::Doc>(
    xml3::Doc::fromString(
        ctx.renderTemplate(
            maps::common::readFileToString(path)))))
{
}

Config::Config(const std::string& path)
    : Config(std::make_shared<xml3::Doc>(
    xml3::Doc::fromFile(path)))
{
}

Config::Config(SharedXmlDoc xml)
    : xml_{std::move(xml)}
    , s3_{xml_->node("/config/s3")}
    , storage_{xml_->node("/config/storage")}
    , updater_{xml_->node("/config/updater")}
{
}

Config Config::fromString(const std::string& config)
{
    return Config(
        std::make_shared<xml3::Doc>(xml3::Doc::fromString(config))
    );
}

std::string Config::toString() const
{
    std::string result;
    xml_->save(result);
    return result;
}

wiki::common::PoolHolder
Config::makePoolHolder() const {
    return wiki::common::PoolHolder{
        xml_->node("/config/databases/database[@id=\"" + DB_ID + "\"]"),
        DB_ID,
        POOL_ID
    };
}

} // maps::fw_updater::config
