#include "module.h"
#include "format.h"

#include <saas/util/network/http_request.h>
#include <util/string/strip.h>

using namespace NUtil;

TJugglerModule::TJugglerModule(const TDeployManagerConfig::TAlertsConfig& alertsConfig)
    : JugglerConfig(alertsConfig.GetJugglerConfig())
    , Enabled(alertsConfig.GetEnabled())
    {};

bool TJugglerModule::SendJugglerRequest(const TString& query, NJson::TJsonValue& result, const TString& data) {
    THttpRequest request(query);
    request.SetTimeout(5000).SetSleepingPause(1000).SetHeader("User-Agent", "Saas-deploy").SetRetryOn5xx(true);
    if (!!data) {
        request.SetPostData(data).SetHeader("Content-Type", "application/json");
    }
    request.SetHeader("Authorization", "OAuth " + JugglerConfig.GetToken());
    THttpReply reply = request.Execute(JugglerConfig.Host, JugglerConfig.Port);
    result = reply.Serialize();
    return reply.IsSuccessReply();
}

bool TJugglerModule::GetAllChecks(NJson::TJsonValue& result, const TMap<TString, TString>& filter) {
    if (!Enabled){
        ERROR_LOG << "calling GetAllChecks with disabled alerts module" << Endl;
        return false;
    }
    TString tag = JugglerConfig.GetCommonTag();
    if (filter.contains("service")) {
        tag += "+.+saas_service_" + filter.at("service");
    }
    if (filter.contains("ctype")) {
        tag += "+.+saas_ctype_" + filter.at("ctype");
    }
    if (filter.contains("skey")) {
        tag += "+.+saas_skey_" + filter.at("skey");
    }
    return SendJugglerRequest("api/checks/checks?do=1&tag_name=" + tag + "&include_notifications=true", result);
}

bool TJugglerModule::CreateSingleCheck(const TJugglerCheck& check, const TVector<TString>& /*owners*/, NJson::TJsonValue& result) {
    if (!Enabled){
        result["error"] = "alerts module is disabled";
        ERROR_LOG << "calling CreateSingleCheck with disabled alerts module" << Endl;
        return false;
    }

    NJson::TJsonValue sendResult;
    bool success = SendJugglerRequest("api/checks/add_or_update?do=1&", sendResult, check.ToString());
    result = NJson::TJsonValue(NJson::JSON_MAP);
    result["juggler_check"] = sendResult;
    return success;
}

bool TJugglerModule::RemoveCheck(const TString& jugglerId, const TString& tag, const TString& golemHost, NJson::TJsonValue& result) {
    if (!Enabled){
        result["error"] = "alerts module is disabled";
        ERROR_LOG << "calling RemoveCheck with disabled alerts module" << Endl;
        return false;
    }
    TString delQuery = "service_name=" + jugglerId;
    if (!tag && !golemHost) {
        result["error"] = "cannot remove checks without tag and golem host";
        return false;
    }
    if (!!tag) {
        delQuery += "&tag_name=" + tag;
    }
    if (!!golemHost) {
        delQuery += "&host_name=" + golemHost;
    }
    return SendJugglerRequest("api/checks/remove_check?do=1&" + delQuery, result);
}
