#include "config.h"

#include <yandex/maps/wiki/configs/editor/attrdef.h>
#include <maps/libs/auth/include/tvm.h>

namespace maps::wiki::merge_poi {
namespace {
const auto EDITOR_URL_XPATH = "/config/services/editor/url"s;
const auto EDITOR_WRITER_URL_XPATH = "/config/services/editor-writer/url"s;
const auto SOCIAL_BACKOFFICE_URL_XPATH = "/config/services/social-backoffice/url"s;
const auto STAT_URL_XPATH = "/config/common/stat/api-url/upload"s;
const auto CATEGORIES_CONFIG_XPATH = "/config/services/editor/config"s;
const auto POI_NM_LANG = "poi_nm:lang";
} // namespace

Config::Config(const common::ExtendedXmlDoc& configXml)
    : configXml_(configXml)
    , editorCfg_(configXml_.get<std::string>(CATEGORIES_CONFIG_XPATH))
    , corePool_(configXml_, "core", "grinder")
    , socialPool_(configXml_, "social", "grinder")
    , editorUrl_(configXml_.get<std::string>(EDITOR_URL_XPATH))
    , editorWriterUrl_(configXml_.get<std::string>(EDITOR_WRITER_URL_XPATH, editorUrl_))
    , socialBackofficeUrl_(configXml_.get<std::string>(SOCIAL_BACKOFFICE_URL_XPATH))
    , statUrl_(configXml_.get<std::string>(STAT_URL_XPATH))
{
}

const std::unordered_set<std::string>&
Config::supportedNmapsLangs() const
{
    static const std::unordered_set<std::string> langs =
        maps::wiki::merge_poi::supportedNmapsLangs(editorCfg_);
    return langs;
}

void Config::initTvm()
{
    auto tvmToolSettings =
        maps::auth::TvmtoolSettings().selectClientAlias("maps-core-nmaps-tasks-sprav");
    auto tvmClient = std::make_shared<NTvmAuth::TTvmClient>(tvmToolSettings.makeTvmClient());

    socialBackofficeTvmTicketProvider_ = [tvmClient]() {
        return tvmClient->GetServiceTicketFor("social-backoffice");
    };
}

std::unordered_set<std::string> supportedNmapsLangs(const EditorCfg& editorCfg)
{
    std::unordered_set<std::string> langs;
    ASSERT(editorCfg.isAttributeDefined(POI_NM_LANG));
    for (const auto& langValue : editorCfg.attribute(POI_NM_LANG)->values()) {
        langs.insert(to_lower(TString(langValue.value)));
    }
    return langs;
}

} // namespace maps::wiki::merge_poi
