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

bool TRTYKIMaker::IncDoc(ui32 actorId) {
    VERIFY_WITH_LOG(KIActors.size() > actorId, "Incorrect TRTYKIMaker usage");
    return KIActors[actorId]->IncDoc();
}

void TRTYKIMaker::Stop() {
    for (ui32 i = 0; i < ActorsCount; ++i) {
        KIActors[i]->Stop();
    }
}

void TRTYKIMaker::Start() {
    TString prefix = Dir + "/" + Prefix;
    for (ui32 i = 0; i < ActorsCount; ++i) {
        KIActors.push_back(new TRTYKIActor(Prefix + "." + ToString(i) + "_", Dir, MergeTaskWriter, MaxPortionDocs));
        KIActors.back()->Start();
    }
}

void TRTYKIMaker::Close(const TVector<ui32>* remapTable) {
    for (ui32 i = 0; i < ActorsCount; ++i) {
        KIActors[i]->Close();
    }
    KIActors.clear();
    MergeTaskWriter.AddOutput(Dir + "/" + Prefix);
    MergeTaskWriter.BuildRemapTable(remapTable);
    {
        TAdvancedIndexMerger aim(MergeTaskWriter.GetTask());
        if (aim.Run()) {
            for (ui32 i = 0; i < MergeTaskWriter.GetTask()->Inputs.size(); ++i) {
                NFs::Remove(MergeTaskWriter.GetTask()->Inputs[i].FilePrefix + "ak");
                NFs::Remove(MergeTaskWriter.GetTask()->Inputs[i].FilePrefix + "ai");
                NFs::Remove(MergeTaskWriter.GetTask()->Inputs[i].FilePrefix + "lk");
                NFs::Remove(MergeTaskWriter.GetTask()->Inputs[i].FilePrefix + "li");
            }
        } else {
            ythrow yexception() << "Incorrect advanced merger behavior";
        }
    }
}

void TRTYKIMaker::Discard() {
    for (auto& actor : KIActors) {
        actor->Discard();
    }
    KIActors.clear();
}
