#pragma once

#include "signals.h"

#include <saas/library/daemon_base/config/watchdog_opts.h>
#include <saas/library/daemon_base/module/module.h>
#include <saas/rtyserver/docfetcher/library/config.h>
#include <library/cpp/mediator/messenger.h>

#include <util/thread/factory.h>

struct TRTYServerConfig;

namespace NFusion {

class TDatacenterChecker;
class TBaseStream;

class TDocFetcherModule : public IDaemonModule, public NMessenger::IMessageProcessor {
public:
    TDocFetcherModule(const IServerConfig& serverConfig);
    ~TDocFetcherModule();

    // This creates clients and spawns a thread to handle communication.  Returns control
    // once the thread spawns, returns false if there is an error during initialization.
    virtual bool Start(const TStartContext& context) override;
    virtual bool Stop(const TStopContext& context) override;

    static bool IsUsedStatic(const IServerConfig& serverConfig) {
        return serverConfig.GetModulesSet().contains(NameStatic());
    }

    static TString NameStatic() {
        static const TString name(DocfetcherModuleName);
        return name;
    }

    virtual TString Name() const override {
        return TDocFetcherModule::NameStatic();
    }

    virtual bool Process(NMessenger::IMessage* message) override;

    ui32 GetMergerTaskCounter() const {
        return AtomicGet(MergerTaskCounter);
    }

private:
    void SetSearchEnabled(bool shouldEnable);

private:
    const TRTYServerConfig& Config;
    const TDocFetcherConfig& FetcherConfig;
    TDocFetcherSignals Signals;
    TLog Log;
    TLog SysLog;

    TAtomicSharedPtr<TDatacenterChecker> PQDatacenterChecker;
    TVector<THolder<TBaseStream>> Streams;

    TMutex SearchBanMutex;
    TAtomic MergerTaskCounter = 0;
    i32 SearchBanCounter = 0;
    bool SearchEnabled = true;

    TMutex CurrentResourceMutex;
    TString CurrentResource;
    TString LastResource;
};

} // namespace NFusion
