#pragma once


#include <kikimr/persqueue/sdk/deprecated/cpp/v2/persqueue.h>

#include <library/cpp/threading/atomic/bool.h>
#include <library/cpp/yconf/conf.h>
#include <library/cpp/json/writer/json_value.h>

#include <util/system/thread.h>

namespace NSaas {
    const TDuration RECOMMENDED_TELEMETRY_INTERVAL = TDuration::Minutes(10);

    using TPQLibPtr = TAtomicSharedPtr<NPersQueue::TPQLib>;

    class TTelemetryConfig {
    private:
        TString Server = "lbkx.logbroker.yandex.net";
        TString Topic;
        TDuration Interval = RECOMMENDED_TELEMETRY_INTERVAL;
        TDuration MaxRandomInterval = TDuration::Minutes(5);

        TDuration ConnectionTimeout = TDuration::Seconds(3);
        TDuration WriteTimeout = TDuration::Seconds(10);

    public:
        virtual ~TTelemetryConfig() = default;

        void SetServer(const TString& value);
        void SetTopic(const TString& value);
        void SetInterval(TDuration value);
        void SetMaxRandomInterval(TDuration value);
        void SetConnectionTimeout(TDuration value);
        void SetWriteTimeout(TDuration value);

        TString GetServer() const;
        TString GetTopic() const;
        TDuration GetInterval() const;
        TDuration GetMaxRandomInterval() const;
        TDuration GetConnectionTimeout() const;
        TDuration GetWriteTimeout() const;

        virtual void Init(const TYandexConfig::Section* section);
        virtual void Print(IOutputStream& so) const;
    };

    class ITelemetry {
    public:
        ITelemetry(
            const TString& applicationName,
            const TTelemetryConfig& config,
            TPQLibPtr pqLib,
            std::shared_ptr<NPersQueue::ICredentialsProvider> credentialsProvider
        );

        virtual ~ITelemetry();

        virtual NJson::TJsonValue GetTelemetryData() const = 0;
        void FillCommonData(NJson::TJsonValue& data) const;
        void Process();

    private:
        TString ApplicationName;
        const TTelemetryConfig Config;
        TPQLibPtr PQLib;

        NPersQueue::TProducerSettings ProducerSettings;

        TManualEvent StopSignal;
        NAtomic::TBool StopFlag;
        THolder<TThread> ProcessThread;

    };
}
