#include "merger_interfaces.h"

void IMergerTask::BuildTempDestinations(IIndexStorage& storage) {
    TempDestinations.clear();
    TmpfsDestinations.clear();
    for (ui32 i = 0; i < GetDestSegments().size(); ++i) {
        TString tmpDests = DoBuildTempDest(storage, GetDestSegments()[i]);
        TempDestinations.push_back(tmpDests);
    }

    for (ui32 i = 0; i < GetDestSegments().size(); i++) {
        TString tmpfsDests = DoBuildTmpfsDest(storage, GetDestSegments()[i]);
        Y_ENSURE(tmpfsDests, "TmpfsDest is null");
        TmpfsDestinations.push_back(tmpfsDests);
    }
    IsTempDestinationsBuilt = true;
}

void IMergerTask::BuildFullDestinations(IIndexStorage& storage) {
    FullDestinations.clear();
    for (ui32 i = 0; i < GetDestSegments().size(); ++i) {
        FullDestinations.push_back(DoBuildFullDest(storage, GetDestSegments()[i]));
    }
    IsFullDestinationsBuilt = true;
}

void IMergerTask::BuildSources(IIndexStorage& storage) {
    Sources.clear();
    for (ui32 i = 0; i < GetSourceSegments().size(); ++i) {
        Sources.push_back(storage.GetFullPath(GetSourceSegments()[i], Path) + GetDirectorySeparator());
    }
    IsSourcesBuilt = true;
}

void IMergerTask::BuildTemp(IIndexStorage& storage) {
    Sources.clear();
    for (ui32 i = 0; i < GetDestSegments().size(); ++i) {
        Sources.push_back(storage.GetFullPath(GetDestSegments()[i], Path) + GetDirectorySeparator());
    }
    IsSourcesBuilt = true;
}

void IMergerTask::AddJsonInfo(NJson::TJsonValue& info) const {
    TGuard<TMutex> g(MutexStatus);
    NJson::TJsonValue mergerProgress;
    for (const auto& i : ProgressInfo) {
        mergerProgress.AppendValue(i);
    }
    info.InsertValue("progress", mergerProgress);
    info.InsertValue("progress_local", ProgressStatus);
    info.InsertValue("status", (ui32)Status);
}

IMerger* TMergerEngine::GetMerger() {
    return Singleton<TMergerEngine>()->Merger;
}

void TMergerEngine::RegisterMerger(IMerger& merger) {
    Singleton<TMergerEngine>()->Merger = &merger;
}

TMergerEngine::TMergerEngine()
    : Merger(nullptr)
{}

TMergerStopGuard::~TMergerStopGuard() {
    TMergerEngine::GetMerger()->Start();
}

TMergerStopGuard::TMergerStopGuard(bool rigid) {
    TMergerEngine::GetMerger()->Stop(rigid);
}
