#include "signals.h"
#include "messages.h"

#include <library/cpp/logger/global/global.h>

#include <util/string/cast.h>

TMaybe<double> TSaasUnistatSignals::GetFloatSignalValue(TUnistat& inst, TStringBuf signal) {
    auto metric = inst.GetSignalValueUnsafe(signal);
    if (!metric || !metric->HasNumber()) {
        return Nothing();
    }
    return metric->GetNumber();
}

void TSaasUnistatSignals::PushSignal(TUnistat& inst, TStringBuf signal, double value) {
    if (!inst.PushSignalUnsafe(signal, value)) {
        DEBUG_LOG << "Not initialized signal: " << signal << Endl;
        inst.PushSignalUnsafe("debug-errors-CTYPE", 1);
    }
}

NUnistat::TPriority TSaasUnistatSignals::Prio(TStringBuf code, bool isService, bool isExtraInfo) {
    int prio = 0;
    if (code == "200" || code.find("xx") != NPOS)
        prio = 50;
    else if (code == "")
        prio = 45;
    else
        prio = 40;
    if (isService)
        prio -= 10;
    if (isExtraInfo)
        prio -= 10;
    return NUnistat::TPriority(prio);
}

void TSaasUnistatSignals::PushSignalWithCode(TUnistat& inst, TStringBuf signal, TStringBuf code, TStringBuf xxCode) {
    PushSignal(inst, TString(signal).append(code), 1);
    PushSignal(inst, TString(signal).append(xxCode), 1);
}

void TSaasProxyUnistatSignals::AddCode(const int code) {
    TString sCode(ToString(code));
    Codes.insert(sCode.substr(0, 1) + "xx");
    Codes.insert(std::move(sCode));
}

void TSaasProxyUnistatSignals::AddService(TString service) {
    Services.insert(std::move(service));
}

void ReportUnistatSignals(IOutputStream& output, int level /*= 0*/) {
    SendGlobalMessageAsync<TMessageUpdateUnistatSignals>();
    output << TUnistat::Instance().CreateJsonDump(level, false);
}
