#include "yt_report.h"

#include <google/protobuf/text_format.h>

#include <util/generic/yexception.h>
#include <util/stream/file.h>


namespace NSaas {

TYTLaunchReport::TYTLaunchReport(const TString& pathToRead) {
    TUnbufferedFileInput reader(pathToRead);
    google::protobuf::TextFormat::Parser protoParser;
    protoParser.AllowUnknownField(true);
    if (!protoParser.ParseFromString(reader.ReadAll(), &ReportProto)) {
        ythrow yexception() << "While creating report from " << pathToRead << ": not a valid protobuf text" << Endl;
    }
}

void TYTLaunchReport::AddTimestamp(ui64 timestamp) {
    ReportProto.SetTimestamp(timestamp);
}

void TYTLaunchReport::Flush(const TString& filePath) {
    TString data;
    if (!google::protobuf::TextFormat::PrintToString(ReportProto, &data)) {
        ythrow yexception() << "Can't serialize report protobuf";
    }

    TUnbufferedFileOutput output(filePath);
    output.Write(data);
}

void TYTLaunchReport::AddError(const TString& error) {
    *ReportProto.AddError() = error;
}

void TYTLaunchReport::AddSensorValue(const TString& sensorName, double value) {
    auto newSensorValue = ReportProto.AddSensors();
    newSensorValue->SetName(sensorName);
    newSensorValue->SetValue(value);
}

void TYTLaunchReport::AddComment(const TString& comment) {
    ReportProto.SetComment(comment);
}

THashMap<TString, double> TYTLaunchReport::GetSignals() const {
    THashMap<TString, double> result;
    auto sensors = ReportProto.GetSensors();
    for (const auto& sensorValue : sensors) {
        result[sensorValue.GetName()] = sensorValue.GetValue();
    }
    return result;
}

const TYTReportProto& TYTLaunchReport::GetReport() const {
    return ReportProto;
}
};
