#include "aggregator.h"

#include <util/string/builder.h>

#include <utility>

namespace NRTYMerger {

    TAggregator::TAggregator(TIndexControllerPtr controller)
        : Controller(std::move(controller))
    {
        Controller->RegisterCallback(this);
    }

    TAggregator::~TAggregator() {
        Deactivate();
    }

    TAggregator::TData TAggregator::Detach() {
        TGuard<TMutex> g1(RemoveMutex), g2(MarkMutex);
        TData result;
        std::swap(Data, result);
        return result;
    }

    void TAggregator::Deactivate() {
        Controller->UnregisterCallback(this); // sync call, no callbacks are running after this point
        Data.RemovedDocIds.clear();
        Data.MarkedDocIds.clear();
    }

    void TAggregator::OnBeforeRemove(const TVector<ui32>& docIds) {
        if (!docIds.size()) {
            return;
        }
        TGuard<TMutex> g(RemoveMutex);
        Data.RemovedDocIds.insert(Data.RemovedDocIds.end(), docIds.cbegin(), docIds.cend());
    }

    void TAggregator::OnBeforeMark(const TVector<ui32>& docIds, ui32 marker) {
        if (!docIds.size()) {
            return;
        }
        TGuard<TMutex> g(MarkMutex);
        TVector<ui32>& docIdsInternal = Data.MarkedDocIds[marker];
        docIdsInternal.insert(docIdsInternal.end(), docIds.cbegin(), docIds.cend());
    }

}
