#include "reply_guard.h"

#include <search/idl/events.ev.pb.h>

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

namespace NProxyMeta {

    TReplyGuard::TReplyGuard(TRTYMetaProtoReportConstructor& reportConstructor, HttpCodes& answeredHttpCode,
        const TSelfFlushLogFramePtr evLog, const bool addEventLogToReport
    )
        : ReportConstructor(reportConstructor)
        , CodeReply(answeredHttpCode)
        , EventLogFrame(evLog)
        , AddEventLogToReport(addEventLogToReport)
    {
        CodeReply = HTTP_CODE_MAX;
    }

    TReplyGuard::~TReplyGuard() noexcept(false) {
        CHECK_WITH_LOG(CodeReply != HTTP_CODE_MAX);
        if (EventLogFrame) {
            EventLogFrame->LogEvent(NEvClass::TReportStarted());
            if (AddEventLogToReport) {
                ReportConstructor.ConsumeLog(EventLogFrame);
            }
        }
        if (ProxyReport) {
            ReportConstructor.Finish(std::move(ProxyReport.GetRef()), CodeReply);
        } else {
            ReportConstructor.Finish(CodeReply);
        }
    }

    void TReplyGuard::SetReplyCode(HttpCodes codeReply) {
        CodeReply = codeReply;
        if (EventLogFrame) {
            EventLogFrame->LogEvent(NEvClass::TDebugMessage(ToString("set HTTP code: ") + HttpCodeStrEx(codeReply)));
        }
    }

    void TReplyGuard::SetProxyReport(NMetaProtocol::TReport&& report) {
        ProxyReport = report;
        if (EventLogFrame) {
            EventLogFrame->LogEvent(NEvClass::TDebugMessage("proxy report"));
        }
    }
}
