#pragma once

#include "aggregators.h"

#include <saas/rtyserver/search/processors/processor.h>
#include <search/rank/docalc_docrelev.h>

#include <util/generic/set.h>
#include <util/generic/map.h>


class TExtendedFacetBuilder: public TRTYFacetBase {
public:
    TExtendedFacetBuilder(const TVector<TString>& expressions)
        : Expressions(expressions.begin(), expressions.end())
    {
        for (const auto& exp : expressions) {
            ParseExpression(exp);
        }
    }

    void Process(ui32 docId, const NGroupingAttrs::TDocsAttrs& da, const TAllDocPositions& positions, const TTRIteratorHitInfos* /*hitInfos*/) override {
        Process(docId, da, &positions);
    }

    void ProcessDoc(ui32 docId, const NGroupingAttrs::TDocsAttrs& da) override {
        Process(docId, da, nullptr);
    }

    void FillProperties(TSearcherProps* props) const override;

private:
    void Process(ui32 docId, const NGroupingAttrs::TDocsAttrs& da, const TAllDocPositions* positions);

private:
    void ParseExpression(const TString& expr);

    typedef TCateg TAttrValue;
    struct TFacetField {
        ui32 Count = 0;
        TString StringValue;
    };

    typedef TMap<TAttrValue, TMinAggregator> TMinFacet;

private:
    const TSet<TString> Expressions;
    TSet<TString> AttrsUsed;
    bool HitsAreUsed;

    TMap<TStringBuf,TMap<TCateg,TString>> Categ2ValueCache;

    TVector<THighAggregator> Aggregators;
};
