#pragma once

#include "factors.h"
#include "parsed_entity.h"

#include <saas/rtyserver/components/generator/builder.h>

#include <saas/rtyserver/common/common_rty.h>
#include <saas/rtyserver/config/fwd.h>
#include <saas/rtyserver/indexer_core/abstract_model.h>
#include <kernel/tarc/dirconf/dirconf.h>

#include <library/cpp/ext/sort.h>

class TSuggestComponentConfig;

class TSuggestIndexBuilder: public TBaseGeneratorBuilder {
public:
    using TSuggestExtSort = TExtSort<TSuggestRecord, TSuggestRecord::TLessByText>;
    using TPtr = TAtomicSharedPtr<TSuggestIndexBuilder>;

private:
    const TSuggestComponentConfig* Config;
    THolder<TSuggestExtSort> SuggestSimple;
    NRTYServer::NSuggest::TFactors FactorsDescription;
    TMutex Mutex;

    static constexpr size_t ExtSortPageSize = 1 << 25;
protected:

    virtual bool DoWriteMeta(NRTYServer::TIndexMetadata& metaData) const override {
        CHECK_WITH_LOG(Config);
        DEBUG_LOG << "Write meta: SuggestClearUnusefulData" << Config->GetClearUnusefulData() << Endl;
        metaData.SetSuggestClearUnusefulData(Config->GetClearUnusefulData());
        return TBaseGeneratorBuilder::DoWriteMeta(metaData);
    }

public:
    TSuggestIndexBuilder(const TDirConf& dirConfig, const TRTYServerConfig& rtyConfig, const TString& componentName);

    virtual bool CheckIndexDocIds(const TString& /*indexPath*/) const override {
        return true;
    }

    virtual void Index(int threadID, const TParsedDocument& document, const ui32 docId) override;
    void Index(const TSuggestRecord& record);

    void SetDocsCount(ui32 docsCount) {
        CHECK_WITH_LOG(!DocsCount);
        DocsCount = docsCount;
    }

    virtual bool DoClose(const NRTYServer::TBuilderCloseContext& context) override;
    bool CloseImpl(const TString& destPath, const TVector<ui32>* remap, const std::atomic<bool>* stopFlag = nullptr);

    virtual bool Start() override {
        return true;
    }
    virtual bool Stop() override {
        return true;
    }
};
