#pragma once

#include <balancer/kernel/process/base_process.h>
#include <balancer/kernel/process/master_main.h>
#include <balancer/kernel/process/messages.h>

#include <balancer/kernel/coro/coroutine.h>
#include <balancer/kernel/ctl/ctl.h>
#include <balancer/kernel/ctl/children_process_common.h>
#include <balancer/kernel/module/module.h>
#include <balancer/kernel/process/children_common/process_stat.h>
#include <balancer/kernel/process_common/main_options.h>
#include <balancer/kernel/rpslimiter/quota.h>
#include <balancer/kernel/pinger/pinger_backend_manager.h>
#include <library/cpp/config/config.h>

#include <util/thread/factory.h>

namespace NSrvKernel {
namespace NDns {
class THelper;
}

namespace NProcessCore {

class TQuotaSyncerProcess
    : public TBaseProcess
{
public:
    TQuotaSyncerProcess(TMainTask& task, const TMainOptions& options, TW2WChannel<TM2CMessage>& m2cChannel);
    ~TQuotaSyncerProcess() override;

    void Execute() override;
    void RecvLoop();
    void Stop();

    void SyncLoop(TString peerName);

    TSharedFiles* SharedFiles() noexcept override;
    TThreadedQueue* ThreadedQueue(const TString& name) noexcept override;
    TPingerManager& SharedPingerManager() noexcept override;
    TLog* GetLog(const TString&) override;
    TLog* GetDynamicBalancingLog() override;
    NProcessCore::TChildProcessType WorkerType() const noexcept override;
    NDns::IResolver& Resolver() noexcept final;
    TContExecutor& Executor() const noexcept override {
        return Executor_->Executor();
    }
    void DumpSharedFiles(NJson::TJsonWriter&) override {}
    void AddGracefulShutdownHandler(IGracefulShutdownHandler*, bool) override {}

    void DoDispose() noexcept override;

private:
    THolder<TOwnExecutor> Executor_;
    THolder<TMainStats> MainStats_;
    THolder<TWorkerCpuStat> WorkerCpuStat_;
    TW2WChannel<TM2CMessage>& M2CChannel_;
    THolder<NDns::TStatsCounters> DnsCounters_;
    THolder<TSharedFiles> SharedFiles_;

    IThreadFactory* ThreadPool_ = SystemThreadFactory();
    TThreadedQueueList ThreadedQueueList_;

    TCoroutine CpuMeasureCoroutine_;
    TCoroutine HealthCheckLoopTask_;
    TCoroutine RecvLoopTask_;
    THolder<NDns::THelper> DnsHelper_;

    NRpsLimiter::TQuotaManager& QuotaManager_;
    TDeque<TCoroutine> QuotaSyncTasks_;
};

}}
