#include "module.h"

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

using namespace NUtil;

TGolovanModule::TGolovanModule(const TDeployManagerConfig::TAlertsConfig& alertsConfig)
    : GolovanConfig(alertsConfig.GetGolovanConfig())
    , Enabled(alertsConfig.GetEnabled())
{ };

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

bool TGolovanModule::GetAlerts(const TMap<TString, TString>& filter, NJson::TJsonValue& result) {
    if (!Enabled){
        result["error"] = "alerts module is disabled";
        ERROR_LOG << "calling GetAlerts with disabled alerts module" << Endl;
        return false;
    }
    TString pattern = JoinStrings(SplitString(GolovanConfig.GetAlertsPrefix(), "."), "%5C.") + "%5C.";
    if (filter.contains("ctype")) {
        pattern += filter.at("ctype") + "%5C.";
    } else {
        pattern += ".*%5C.";
    }
    if (filter.contains("service")) {
        pattern += filter.at("service") + "%5C.";
    }
    bool success = SendGolovanRequest("list?name_pattern=" + pattern, result);
    if (success && filter.contains("akey")) {
        NJson::TJsonValue newList(NJson::JSON_ARRAY);
        for (auto& i : result["content"]["response"]["result"].GetArray()) {
            if (i["name"].GetString().Contains(filter.at("akey"))) {
                newList.AppendValue(i);
            }
        }
        result["content"]["response"]["result"] = newList;
        result["content"]["response"]["total"] = newList.GetArray().ysize();
    }
    return success;
}

bool TGolovanModule::CreateSingleAlert(const TYasmAlert& alert, NJson::TJsonValue& result) {
    if (!Enabled){
        result["error"] = "alerts module is disabled";
        ERROR_LOG << "calling CreateSingleAlert with disabled alerts module" << Endl;
        return false;
    }
    const TString data = alert.ToString();
    bool createSuccess = SendGolovanRequest("create?name=" + alert.GetId(), result, data);
    if (!createSuccess && result["code"].GetUInteger() >= 400 && result["code"].GetUInteger() < 500) {
        result["operation"] = "updating alert after 4xx on create";
        return SendGolovanRequest("update?name=" + alert.GetId(), result, data);
    } else {
        result["operation"] = "creating alert";
        return createSuccess;
    }
}

bool TGolovanModule::RemoveAlert(const TString& id, NJson::TJsonValue& result) {
    if (!Enabled){
        result["error"] = "alerts module is disabled";
        ERROR_LOG << "calling RemoveAlert with disabled alerts module" << Endl;
        return false;
    }
    return SendGolovanRequest("delete?name=" + id, result, " ");
}
