#include "merger.h"

#include <saas/rtyserver/config/common_indexers_config.h>
#include <saas/rtyserver/config/config.h>
#include <saas/rtyserver/config/searcher_config.h>
#include <saas/rtyserver/model/component.h>

#include <robot/library/oxygen/indexer/processor/arcdir/arcdir.h>

#include <saas/rtyserver/merger/library/merger.h>

bool TOxyArchiveMerger::DoMerge(const NRTYServer::TMergeContext& context, const TRTYServerConfig& config) {
    TRTYMerger::TContext mc(context.Context);
    ui64 operation = 0;
    switch (config.GetSearcherConfig().ArchiveType) {
    case AT_FLAT:
        operation = TRTYMerger::otArch;
        break;
    case AT_MULTIPART:
    {
        operation = TRTYMerger::otMpArch;
        mc.MultipartMergerContext.Reset(new NRTYArchive::TMultipartMergerContext(config.GetCommonIndexers().TextArchiveParams));
        mc.MultipartArcFile = "index" + Prefix + "arc";
        break;
    }
    default:
        FAIL_LOG("Unknown archive type");
    }
    TRTYMerger rtyMerger(context.RigidStopSignal, operation);
    // Lock indexation on callback after archive merge
    mc.AdditionalSuffixIndexName = Prefix;
    mc.IgnoreNoAttrs = true;
    return rtyMerger.MergeIndicies(mc);
}

bool TOxyArchiveMerger::DoInitialize() {
    NOxygen::TArcDirProcessor* proc = dynamic_cast<NOxygen::TArcDirProcessor*>(Processor.Get());
    CHECK_WITH_LOG(proc);
    Prefix = TFsPath(proc->GetArcFile()).GetName();
    if (!Prefix.StartsWith("index")) {
        ERROR_LOG << "Incorrect prefix for arc merger: " << Prefix << Endl;
        return false;
    } else {
        INFO_LOG << "Prefix for arc merger: " << Prefix << Endl;
    }
    Prefix = Prefix.substr(5, Prefix.size() - 8);
    return true;
}

TOxyArchiveMerger::TFactory::TRegistrator<TOxyArchiveMerger> TOxyArchiveMerger::Registrator("TArcDirProcessor");
