#include "local_indexer.h"

#include <util/generic/yexception.h>

void TLocalIndexer::TOptions::BindToOpts(NLastGetopt::TOpts& opts) {
    opts.AddLongOption("srcdir", "path to directory containing documents for indexing")
        .RequiredArgument("SRCDIR").StoreResult(&SrcDir)
        .Required();
    opts.AddLongOption("srctype", "type of input files: msgdoc, action")
        .RequiredArgument("TYPE").StoreResult(&SrcType)
        .DefaultValue(SrcType);
    opts.AddLongOption("srcsuffix", "suffix of protobuf document files")
        .RequiredArgument("SUFFIX").StoreResult(&SrcSuffix)
        .DefaultValue(SrcSuffix);

    opts.AddLongOption("merge", "merge index segements after indexing")
        .NoArgument().StoreResult(&DoMerge, true)
        .DefaultValue(DoMerge ? "true" : "false");
}

TLocalIndexer::TLocalIndexer(TString configText, const TOptions& options)
        : Options(options)
        , ConfigText(configText)
{
    if (Options.SrcType == "msgdoc") {
        Builder.Reset(new TMsgDocFileDocumentBuilder(Options.SrcDir, Options.SrcSuffix));
    } else if (Options.SrcType == "action") {
        Builder.Reset(new TActionFileDocumentBuilder(Options.SrcDir, Options.SrcSuffix));
    } else {
        ythrow yexception() << "unknown type: " << Options.SrcType;
    }
}

void TLocalIndexer::Run() {
    TStandaloneIndexer standaloneIndexer(ConfigText);
    standaloneIndexer.EnableIndexing();
    NRTYServer::TMessage::TDocument document;
    while (Builder->GetNext(document)) {
        if (!document.HasModificationTimestamp()) {
            document.SetModificationTimestamp(time(nullptr));
        }
        standaloneIndexer.Index(document);
    }
    standaloneIndexer.DisableIndexing();
    if (Options.DoMerge) {
        standaloneIndexer.EnableMerging();
        standaloneIndexer.Merge();
        standaloneIndexer.DisableMerging();
    }
}
