#include "monitor.h"

namespace NWebmaster {

void MonitorPushHistory(const TString &suffix, const TMap<time_t, TMap<TString, double>> &history, const TString &prefix) {
    TSolomonPushBackend pushBackend("webmaster", "webmaster_performance_" + suffix);
    TMonitoringAgent<TSolomonPushBackend> agent(pushBackend);

    for (const auto &day : history) {
        const time_t timestamp = day.first;

        for (const auto& record : day.second) {
            const TString &source = record.first;
            const double &value = record.second;

            agent
                .Next(prefix + source, value) //daily anomalies
                .Timestamp(TInstant::Seconds(timestamp));
        }
    }

    agent
        .GlobalService("webmaster_quality")
        .Commit();
}

void MonitorPushLabel(const TString &suffix, const TString &label, const TString &service, double value) {
    TSolomonPushBackend pushBackend("webmaster", "webmaster_performance_" + suffix);
    TMonitoringAgent<TSolomonPushBackend> agent(pushBackend);

    agent
        .Next(label, value)
        .GlobalService(service)
        .Commit();
}

void MonitorPushQualityLabel(const TString &suffix, const TString &label, double value) {
    MonitorPushLabel(suffix, label, "webmaster_quality", value);
}

void MonitorPushCountersLabel(const TString &suffix, const TString &label, double value) {
    MonitorPushLabel(suffix, label, "webmaster_counters", value);
}

void UpdateHistoryMonitor(NYT::IClientBasePtr client, const TString &suffix, const TString &historyTable, const TString &prefix) {
    TMap<time_t, TMap<TString, double>> history;

    auto reader = client->CreateTableReader<NYT::TYaMRRow>(historyTable);
    for (; reader->IsValid(); reader->Next()) {
        const NYT::TYaMRRow &row = reader->GetRow();
        time_t timestamp = FromString<time_t>(TString{row.Key});
        TString source = TString{row.SubKey};
        double value = FromString<double>(TString{row.Value});
        history[timestamp][source] = value;
    }

    MonitorPushHistory(suffix, history, prefix);
}

} //namespace NWebmaster
