#pragma once

#include "config.h"

#include <yweb/robot/kiwi/export/subscribersrv.h>
#include <yweb/robot/kiwi/clientlib/subscriber.h>

#include <saas/library/daemon_base/metrics/servicemetrics.h>
#include <saas/util/logging/replies.h>
#include <library/cpp/mediator/messenger.h>
#include <saas/util/queue.h>

#include <util/generic/queue.h>
#include <util/generic/deque.h>
#include <util/system/event.h>

class TTaskExecutor;

namespace NSaas {
    class IExportProcessor;

    class TKiwiExport;
    struct TIncomingExportCtx;
    struct TIncomingDocumentCtx;

    class TSubscriber: public NKiwi::NExport::IHandler {
    public:
        TSubscriber(TKiwiExport& exporter, NKiwi::NExport::TCookieWriter& cookieWriter);
        TLog& GetLog();

    protected:
        virtual void DoHandle(TAutoPtr<NKiwi::TBusExportMessage> msg);

    private:
        TKiwiExport& Exporter;
        NKiwi::NExport::TCookieWriter& CookieWriter;
    };

    class TKiwiExport: public IMessageProcessor {
    public:
        TKiwiExport(const TKiwiExportConfig& config, TTaskExecutor& executor);
        ~TKiwiExport();
        void Start();
        void Stop();

        void ProcessRecord(const TIncomingExportCtx& ctx, const NKwExport::TExportRecord& record) const;
        void IndexDocument(const TIncomingExportCtx& exportCtx, TIncomingDocumentCtx documentCtx) const;

        // IMessageProcessor
        virtual TString Name() const;
        virtual bool Process(IMessage* message);

        TLog& GetLog() const {
            return Log;
        }
        TDynamicServiceMetrics& GetExportMetrics() {
            return ExportMetrics;
        }
        TDynamicServiceMetrics& GetServiceMetrics() {
            return ServiceMetrics;
        }
    private:
        using TProcessors = TMap<TString, TSimpleSharedPtr<IExportProcessor>>;

    private:
        const TKiwiExportConfig& Config;
        TTaskExecutor& TaskExecutor;
        THolder<NKiwi::NExport::TSubscriberServer> Server;
        THolder<NKiwi::NExport::TCookieWriter> CookieWriter;
        THolder<NKiwi::NExport::TMonCounters> MonitoringCounters;
        THolder<TSubscriber> Subscriber;

        mutable TLog Log;
        mutable TAutoEvent DocIndexedEvent;
        TDynamicServiceMetrics ServiceMetrics;
        TDynamicServiceMetrics ExportMetrics;
        mutable NUtil::TRepliesStorage RepliesStorage;

        TProcessors Processors;
        TSimpleSharedPtr<IExportProcessor> UnknownProcessor;
        TString ExportTypeTuple;
        TString DefaultExportType;
    };
}
