#pragma once

#include "cs_component.h"
#include <saas/rtyserver/factors/factors_mask.h>
#include <saas/rtyserver/indexer_core/abstract_model.h>
#include <util/generic/string.h>
#include <ysite/yandex/posfilter/hits_loader.h>
#include <ysite/yandex/posfilter/tr_iterator.h>
#include <saas/rtyserver/components/erf/erf_disk.h>
#include <saas/rtyserver/components/erf/erf_writer.h>
#include <saas/rtyserver/config/config.h>
#include <saas/rtyserver/config/searcher_config.h>

class TCSManager: public NRTYServer::IIndexComponentManager {
private:
    const TRTYServerConfig& Config;
    const NRTYFactors::TCSFactorsHashList& FactorsList;
    TString Dir;
    TVector<NRTYFactors::TCSFactorsList::TPtr> FactorsInfo;
    TVector<TNamedBlocksErf::TPtr> NamedBlockErfs;
    const TVector<ui32>* RemapTable;
public:

    typedef TAtomicSharedPtr<TCSManager> TPtr;

    TCSManager(const TString& dir, const TRTYServerConfig& config)
        : NRTYServer::IIndexComponentManager(CS_COMPONENT_NAME)
        , Config(config)
        , FactorsList(Config.GetSearcherConfig().Factors->GetCommonStatFactors())
        , Dir(dir)
    {
        RemapTable = nullptr;
        for (NRTYFactors::TCSFactorsHashList::const_iterator i = FactorsList.begin(), e = FactorsList.end(); i != e; ++i) {
            FactorsInfo.push_back(i->second);
            NamedBlockErfs.push_back(new TNamedBlocksErf(Dir, Config, i->second->GetFactorsInfo(), i->first, !dir, CS_COMPONENT_NAME));
        }
    }

    bool SetRemapTable(const TVector<ui32>* remapTable);
    bool DoOpen() override;
    bool DoClose() override;
    bool CloseWithResort(const TVector<ui32>* remapTable);
    ui32 GetDocumentsCount() const override;
    void InitInteractions(const NRTYServer::IIndexManagersStorage& /* storage */) override;
    bool GetDocInfo(const ui32 docId, NJson::TJsonValue& result) const override;
    bool UpdateDoc(ui32 docId, const TParsedDocument::TPtr doc) override;

    void Add(const TParsedDocument& document, const ui32 docId, bool replace = false);
    void CalcFactors(TCalcFactorsContext& ctx, const NRTYFactors::TRTYFactorMask* rtyFactorMask) const;
};
