#pragma once

#include "thread_loop.h"

#include <saas/library/daemon_base/metrics/metrics.h>
#include <saas/library/daemon_base/config/watchdog_opts.h>
#include <saas/rtyserver/common/stream_data.h>
#include <saas/util/logging/tskv_log.h>
#include <library/cpp/mediator/messenger.h>

#include <util/generic/ptr.h>

class TLog;

namespace NFusion {
    class TDocFetcherModule;
    struct TBaseStreamConfig;

    class TBaseStream
        : public IThreadLoop
        , public IMessageProcessor
        , protected IWatchdogOptionSubscriber
    {
    public:
        TBaseStream(const TDocFetcherModule& owner, const TBaseStreamConfig& config, TLog& log, const TString& name);
        virtual ~TBaseStream() = default;

        virtual void SubscribeToWatchdog(IWatchdogOptions& w);

        const TString& GetStreamName() const;

    protected:
        virtual void OnStreamStart() = 0;
        virtual void OnStreamBeforeStop() = 0;
        virtual void OnStreamStop() = 0;
        virtual TDuration GetDelay() const = 0;
        virtual TTimeToSleep DoStreamIteration() = 0;

        virtual void OnWatchdogOption(const TString& key, const TString& value) override;

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

        NRTYServer::TTimestampSnapshot GetTimestampSnapshot() const;
        NRTYServer::TPositionsSnapshot GetPositionsSnapshot() const;
        TDuration GetDelayFromSubStream(const NRTYServer::TTimestampSnapshot& snapshot, ui32 substream) const;

        void DisableSearch();
        void EnableSearch();
        bool SearchDisabledByStream();

        void ReopenIndexers();

    private: //IThreadLoop
        void OnBeforeStart() final;
        void OnAfterStart() final;
        void OnBeforeStop() final;
        void OnAfterStop() final;
        void OnPause() final;
        void OnResume() final;
        //TTimeToSleep OnException() final;
        TTimeToSleep DoIteration() final;

    protected:
        const TBaseStreamConfig& BaseConfig;
        TLog& Log;

    private:
        ui32 SearchDisabled;
        bool AsyncStart;
        const TDocFetcherModule& Owner;
    };
}
