#include "common.h"
#include "processor.h"

#include <saas/api/export/jsondocarray.pb.h>
#include <saas/indexerproxy/adapters/json_to_rty/json_to_rty_adapter.h>
#include <saas/indexerproxy/export/config.pb.h>

#include <yweb/robot/kiwi/protos/export.pb.h>

namespace NSaas {
    class TJsonExportProcessor: public TCommonExportProcessor {
    private:
        const TString JsonDocsArrayTuple;
    public:
        TJsonExportProcessor(const NSaas::TExportTypeOptions& type)
            : TCommonExportProcessor(type)
            , JsonDocsArrayTuple(type.GetJsonDocsTuple())
        {
        }

        TIncomingDocumentCtxPack Process(const NKwExport::TExportRecord& record) const override {
            NKiwi::TKiwiObject object(record.GetData());
            const NKiwi::NTuples::TTuple* tuple = object.FindByLabel(JsonDocsArrayTuple.data());
            if (!tuple) {
                throw yexception() << "cannot find tuple " << JsonDocsArrayTuple;
            }

            NSaas::TJsonDocumentArray documentArray;
            if (!documentArray.ParseFromArray(tuple->GetData(), tuple->GetSize()))
                throw yexception() << "cannot parse protobuf from kiwi tuple";

            NSaas::TIncomingDocumentCtxPack result;

            ::google::protobuf::RepeatedPtrField<NSaas::TJsonDocument>::const_iterator document = documentArray.GetDocuments().begin();
            ::google::protobuf::RepeatedPtrField<NSaas::TJsonDocument>::const_iterator end = documentArray.GetDocuments().end();
            for (; document != end; ++document) {
                const TString& service = document->GetService();
                if (document->HasErrorMessage()) {
                    ERROR_LOG << "status=trigger_error;service=" << service << ";message=" << document->GetErrorMessage() << Endl;
                    continue;
                }

                NSaas::TIncomingDocumentCtx documentCtx = CreateContext(record);
                documentCtx.Service = service;
                documentCtx.Adapter = NIndexerProxy::TJsonToRTYAdapter::AdapterAlias;
                documentCtx.Data = TBlob::FromString(document->GetJson());
                result.push_back(documentCtx);
            }

            return result;
        }
    };
}

NSaas::TExportProcessorFactory::TRegistrator<NSaas::TJsonExportProcessor> Index("Index");
