#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 TTrigramDocsMap {
public:
    using TPtr = TAtomicSharedPtr<TTrigramDocsMap>;

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 Empty() const;
};

class TTrigramIndexManagerMemory: public TTrigramIndexManager {
private:
    TRWMutex Mutex;
    THashMap<TString, TTrigramDocsMap::TPtr> Map;
    bool RemoveDoc(ui32 docId);
    class TMemoryIterator;

public:
    TTrigramIndexManagerMemory(const TRTYServerConfig& config)
        : TTrigramIndexManager(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 TIterator::TPtr CreateIterator(const TString& keyName, const TString& value, const IDocProcessor* filter) const override;
};
