#pragma once
#include "merger.h"
#include "doc_infos.h"
#include <library/cpp/streams/special/buffered_throttled_file.h>
#include <library/cpp/logger/global/global.h>
#include <kernel/m2n/groupattrs.h>

class TAttrsMerger : public TRTYMerger::IMergerOperator, public NM2N::IOutputStreamsBuilder {
private:
    const TRTYMerger::TContext* Context;
public:
    TString GetName() const override {
        return "GRAttrs";
    }

    IOutputStream* BuildStream(const TString& filename) override {
        return new TBufferedThrottledFileOutputStream(filename, Context->WriteOption);
    }

    bool Merge(const std::atomic<bool>* /*stopKey*/, TMergeDocInfos& infos, const TRTYMerger::TContext& context) override {
        Context = &context;
        TVector<const char*> inputFiles;
        TVector<const char*> outputFiles;
        for (size_t i = 0; i < context.Sources.size(); ++i) {
            inputFiles.push_back(context.Sources[i].data());
        }
        for (size_t i = 0; i < context.Dests.size(); ++i) {
            outputFiles.push_back(context.Dests[i].data());
        }
        try {
            NM2N::TCompactMultipleRemapTable remapTable;
            TMergeDocInfos::TDocInfoSource source = infos.GetIterator();
            NM2N::LoadRemapTableFromSource(remapTable, source);
            NM2N::TAttrsRemap remap(&inputFiles[0], &outputFiles[0], &remapTable, context.IgnoreNoAttrs, context.IndexaaVersion);
            remap.SetOutputStreamsBuilder(this);
            remap.Remap();
            remap.WriteResult();
        } catch (const yexception& e) {
            ERROR_LOG << "Error while remap GRAttrs:" << e.what() << Endl;
            return false;
        }
        if (context.Callback)
            context.Callback->OnAfterGrAttrMerge();
        return true;
    }
};

