#pragma once

#include "manager.h"
#include <saas/util/types/longhash.h>
#include <util/generic/ptr.h>
#include <util/generic/set.h>
#include <util/system/rwlock.h>

class TSpecialKeyDocsMap {
public:
    using TPtr = TAtomicSharedPtr<TSpecialKeyDocsMap>;
private:
    THashMap<TString, TSet<SUPERLONG>> PositionsByHash;
    THashMap<ui32, TSet<TString>> HashesByDoc;
    TRWMutex Mutex;
public:

    ui32 RemoveDoc(ui32 docId);

    bool AddData(const TString& value, const TSet<SUPERLONG>& positions);

    bool GetData(const TString& value, TSet<SUPERLONG>& positions) const;

    bool HasKey(const TString& value) const;

    bool Empty() const;

    void GetValues(TSet<TString>& result) const;
};

class TKeysIndexManagerMemory: public TKeysIndexManager {
private:
    TRWMutex Mutex;
    THashMap<TString, TSpecialKeyDocsMap::TPtr> Map;
    bool RemoveDoc(ui32 docId);
    class TMemoryIterator;
public:

    TKeysIndexManagerMemory(const TRTYServerConfig& config)
        : TKeysIndexManager(config)
    {

    }

    virtual bool DoOpen() override {
        return true;
    }

    virtual bool DoClose() override {
        return true;
    }

    virtual ui32 RemoveDocids(const TVector<ui32>& docids) override;

    bool AddData(const TString& keyName, const TString& value, const TSet<SUPERLONG>& positions);

    virtual bool GetData(const TString& keyName, const TString& value, const IDocProcessor* filter, TSet<SUPERLONG>& result) const override;

    virtual bool HasKey(const TString& keyName, const TString& value) const override;

    virtual TIterator::TPtr CreateIterator(const TString& keyName, const TString& value, const IDocProcessor* filter) const override;

    virtual void GetKeyValues(const TString& keyName, TSet<TString>& result) const override;
};

