#pragma once

#include <balancer/kernel/stats/manager.h>

#include <infra/yp_service_discovery/libs/sdlib/client.h>
#include <infra/yp_service_discovery/libs/sdlib/http_resolver.h>

#include <library/cpp/config/sax.h>

#include <util/datetime/base.h>

namespace NSrvKernel {
    class ICtl;

    struct TSDConfig
        : public NConfig::IConfig::IFunc
        , public NYP::NServiceDiscovery::TSDConfig
    {
    public:
        using NYP::NServiceDiscovery::TSDConfig::TSDConfig;

        TSDConfig() = default;

        explicit TSDConfig(NConfig::IConfig& config)
        {
            config.ForEach(this);
        }
    private:
        START_PARSE {
            TString tmp;
            ON_KEY("update_frequency", tmp) {
                SetUpdateFrequency(tmp);
                return;
            }
            ON_KEY("host", tmp) {
                SetHost(tmp);
                return;
            }
            ON_KEY("port", tmp) {
                SetPort(FromString(tmp));
                return;
            }
            ON_KEY("cached_ip", tmp) {
                SetCachedIp(tmp);
                return;
            }
            ON_KEY("connect_timeout", tmp) {
                SetConnectTimeout(tmp);
                return;
            }
            ON_KEY("request_timeout", tmp) {
                SetRequestTimeout(tmp);
                return;
            }
            ON_KEY("cache_dir", tmp) {
                SetCacheDir(tmp);
                return;
            }
            ON_KEY("log", tmp) {
                SetLog(tmp);
                return;
            }
            ON_KEY("client_name", tmp) {
                SetClientName(tmp);
                return;
            }
            ON_KEY("background_update_check_frequency", tmp) {
                return;
            }
            ON_KEY("allow_empty_endpoint_sets", tmp) {
                SetAllowEmptyEndpointSetsOnStart(FromString(tmp));
                return;
            }
        } END_PARSE
    };

    class TSDStatCounterImpl;
    using TCounters = TDeque<TAtomicSharedPtr<TSDStatCounterImpl>>;

    class TSDManager
        : TSDConfig
        , TCounters
        , public NYP::NServiceDiscovery::TSDClient
    {
    public:
        TSDManager() = default;
        TSDManager(NConfig::IConfig& config, TSharedStatsManager& statsManager);
        TSDManager(const NYP::NServiceDiscovery::TSDConfig& config, TSharedStatsManager& statsManager);
        ~TSDManager();


        void Start();

        const TSDConfig& GetConfig() const {
            return *this;
        }

        void ReopenLog();
    private:
        void SwitchStat(size_t workerId);

        TCounters Counters_;
        THolder<TLog> Log_;
    };
}

