#pragma once
#include "configs.h"

#include <library/cpp/threading/hot_swap/hot_swap.h>
#include <library/cpp/threading/cron/cron.h>

#include <util/generic/ptr.h>

namespace NSaas {
    class TPersQueueWriter;
}

namespace NSaasPush {

class TServiceWriter;

class TSearchMapStorage {
    public:
        using TServicesByCtype = THashMap<TString, TSet<TString>>;
        TSearchMapStorage(
            const TVector<NSaas::TSearchMapInputSettings>& searchMapSettings,
            const TVector<TServiceInfo>& services,
            TDuration updatePeriod
        );

        std::optional<NSearchMapParser::TSearchMap> GetSearchMap(const TString& ctype) const;
        void Stop();
        void AddSubscriber(TServiceWriter* writer);
        void RemoveSubscriber(TServiceWriter* writer);

    private:
        struct TImpl : public TThrRefBase {
            TImpl(
                const TVector<NSaas::TSearchMapInputSettings>& searchMapSettings,
                const TServicesByCtype& filter);

            THashMap<TString, NSearchMapParser::TSearchMap> SearchMapByCtype;
        };

        void RecreateImpl();

        THotSwap<TImpl> Impl;
        NCron::IHandlePtr Updater;

        TMutex SubscribersMutex;
        THashSet<NSaasPush::TServiceWriter*> Subscribers;

        const TVector<NSaas::TSearchMapInputSettings>& SearchMapSettings;
        TServicesByCtype ServiceByCtype;
    };
}
