#include "qs_builder.h"
#include "qs_component.h"

#include <saas/rtyserver/config/common_indexers_config.h>
#include <saas/rtyserver/config/config.h>
#include <saas/rtyserver/config/indexer_config.h>

void TQSBuilder::Index(int threadID, const TParsedDocument& document, const ui32 docId) {
    const TQSParsedEntity* qsEntity = document.GetComponentEntity<TQSParsedEntity>(QS_COMPONENT_NAME);
    if (!qsEntity) {
        return;
    }
    const THashMap<TString, TDocumentQSInfo>& docInfos = qsEntity->GetDocInfos();
    for (THashMap<TString, TDocumentQSInfo>::const_iterator i = docInfos.begin(), e = docInfos.end(); i != e; ++i) {
        TMakers::iterator itMaker = Makers.find(i->first);
        VERIFY_WITH_LOG(itMaker != Makers.end(), "TQSBuilder::Index failed");
        itMaker->second->Make(threadID, i->second, docId);
    }
}

bool TQSBuilder::DoClose(const NRTYServer::TBuilderCloseContext& context) {
    VERIFY_WITH_LOG(context.SrcDir == context.DstDir, "Not supported");
    for (TMakers::iterator i = Makers.begin(), e = Makers.end(); i != e; ++i) {
        i->second->Close(context);
    }
    return true;
}

bool TQSBuilder::Start() {
    const NRTYFactors::TQSFactorsHashList& factors = Config.Common.Owner.GetSearcherConfig().Factors->GetQuerySpecFactors();
    for (NRTYFactors::TQSFactorsHashList::const_iterator i = factors.begin(), e = factors.end(); i != e; ++i) {
        Makers[i->first] = new TQSMaker(Config.Threads, Dir, i->second->GetFactorsInfo(), i->first);
        Makers[i->first]->Start();
    }
    return true;
}

bool TQSBuilder::Stop() {
    for (TMakers::iterator i = Makers.begin(), e = Makers.end(); i != e; ++i) {
        i->second->Stop();
    }
    return true;
}

void TQSBuilder::DoDiscard() {
    for (auto& maker : Makers) {
        maker.second->Discard();
    }
}
