#include "processor.h"

#include <saas/api/clientapi.h>
#include <saas/indexerproxy/adapters/proto_adapter/proto_adapter.h>
#include <saas/indexerproxy/export/config.pb.h>

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

namespace {
    class TVoidExportProcessor: public NSaas::IExportProcessor {
        NSaas::TIncomingDocumentCtxPack Process(const NKwExport::TExportRecord& record) const override {
            NSaas::TAction action;
            action.GetDocument().SetUrl(record.GetKey());
            NSaas::TIncomingDocumentCtx fake(record);
            fake.Adapter = NIndexerProxy::TProtoAdapter::AdapterAlias;
            fake.Service = "unknown_export_type";
            fake.Data = TBlob::FromString(action.ToProtobuf().SerializeAsString());

            return { fake };
        }
    };

    NSaas::EAckMode GetAckMode(const NSaas::TExportTypeOptions& exportType) {
        auto mode = exportType.GetAckMode();
        switch (mode) {
        case NSaas::TExportTypeOptions::DEFAULT: return NSaas::EAckMode::Default;
        case NSaas::TExportTypeOptions::INVERSE: return NSaas::EAckMode::Inverse;
        case NSaas::TExportTypeOptions::ALWAYS:  return NSaas::EAckMode::Always;
        default: FAIL_LOG("Unknown Ack mode");
        }
    }
}

TAutoPtr<NSaas::IExportProcessor> NSaas::CreateExportProcessor(const NSaas::TExportTypeOptions& exportType) {
    return NSaas::TExportProcessorFactory::Construct(exportType.GetProcessor(), exportType);
}

TAutoPtr<NSaas::IExportProcessor> NSaas::CreateDefaultExportProcessor() {
    return new TVoidExportProcessor;
}

NSaas::TCommonExportProcessor::TCommonExportProcessor(const NSaas::TExportTypeOptions& exportType)
    : AckMode(GetAckMode(exportType))
{
}

NSaas::TIncomingDocumentCtx NSaas::TCommonExportProcessor::CreateContext(const NKwExport::TExportRecord& record) const {
    NSaas::TIncomingDocumentCtx ctx(record);
    ctx.AckMode = AckMode;
    return ctx;
}
