#include "report.h"
#include "reply_data.h"

#include <saas/searchproxy/common/cgi.h>
#include <saas/searchproxy/report/new/formatter.h>
#include <saas/searchproxy/report/new/converter.h>

#include <search/grouping/groupinfo.h>

namespace NProxyMeta {
    TRTYMetaProtoReportConstructor::TRTYMetaProtoReportConstructor(IReportBuilderContext& context)
        : TBase(context)
    {
        const TCgiParameters& cgi = context.GetCgiParameters();

        TGroupingParams grouping;
        if (cgi.Has(NSearchProxyCgi::g)) {
            grouping.Parse(cgi.Get(NSearchProxyCgi::g).c_str());
        }
        if (grouping.gMode == GM_DEEP) {
            GroupingOverride = grouping.gAttr;
        }
    }

    void TRTYMetaProtoReportConstructor::AddDocumentToGroup(NMetaProtocol::TDocument& doc, const TString& grouping, const TString& category) {
        if (!grouping && GroupingOverride) {
            TBase::AddDocumentToGroup(doc, GroupingOverride, category);
        } else {
            TBase::AddDocumentToGroup(doc, grouping, category);
        }
    }

    void TRTYMetaProtoReportConstructor::FinishImpl(NMetaProtocol::TReport& report, const ui32 httpCode) {
        IReportBuilderContext& context = GetContext();
        const TCgiParameters& cgi = context.GetCgiParameters();

        const TString& reportFormat = cgi.Get("report_format");
        if (reportFormat) {
            IReportFormatter::TPtr formatter = IReportFormatter::TFactory::Construct(reportFormat, cgi);
            if (!formatter) {
                const TString err = "Unknown report format";
                context.MakeSimpleReply(TBuffer(err.data(), err.size()), HTTP_BAD_REQUEST);
                return;
            }

            InsertErrors(report);
            InsertEventLog(report);

            TSearchReplyData replyData(report);
            TReportConstructor constructor(replyData, context);
            constructor.BuildReport(*formatter);
            formatter->FillHeaders(context);
            context.MakeSimpleReply(formatter->GetResult(), httpCode);
        } else {
            TBase::FinishImpl(report, httpCode);
        }
    }
}
