#pragma once

#include <saas/util/smartqueue_ng.h>
#include <library/cpp/mediator/messenger.h>
#include <util/generic/map.h>
#include <util/generic/vector.h>
#include <util/system/mutex.h>

//
// Class for collecting stats
//
class TRTYPoolsStat final: public IMessageProcessor {
public:
    using TRef = TAtomicSharedPtr<TRTYPoolsStat>;
    using TStatHandlerRef = NUtil::TSmartMtpQueueNg::TStatHandlerRef;

    static constexpr size_t MaxLogLines = 320; // per loadtype
    static constexpr size_t MaxLogPeriod = 600; // in seconds

private:
    using IStatHandler = NUtil::TSmartMtpQueueNg::IStatHandler;
    using TStats = IStatHandler::TStats;

    class THandler final: public IStatHandler {
        TRef Parent;
        TString Loadtype;
        TString Id;

    public:
        inline THandler(TRef parent, const TString& loadtype, const TString& id)
            : Parent(parent)
            , Loadtype(loadtype)
            , Id(id)
        {
            Y_ASSERT(parent);
        }

        virtual void OnStats(const TStats& data) override {
            Parent->OnStats(Loadtype, Id, data);
        }
    };

    struct TStatRecord {
        TInstant Time;
        TString Id;
        TStats Data;
    };

private:
    TMap<TString, TVector<TStatRecord>> Data;
    TMutex Mutex;


public:
    TRTYPoolsStat();
    virtual ~TRTYPoolsStat();

    void Purge();

    static TStatHandlerRef CreateHandler(TRef& ref, const TString& loadtype, const TString& id);

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

private:
    static TString Format(const TStatRecord& rec);

    // Interface for THandler
    void OnStats(const TString& name, const TString& id, const IStatHandler::TStats& data);
};
