#include "data_normalizer.h"
#include "component.h"
#include "disk_manager.h"

TArchiveDataNormalizer::TArchiveDataNormalizer(const TRTYServerConfig& config, const TRTYFullArchiveConfig& componentConfig)
    : NRTYServer::INormalizer(config)
    , ComponentConfig(componentConfig)
{}

const char* TArchiveDataNormalizer::Name() const {
    return "FADataNormalizer";
}

bool TArchiveDataNormalizer::AllRight(const NRTYServer::TNormalizerContext& context, const THolder<TFileMap>&) const {
    {
        const TDiskFAManager* mngr = context.Managers.GetManager<TDiskFAManager>(FULL_ARCHIVE_COMPONENT_NAME);
        if (mngr && !mngr->IsOpened()) {
            ERROR_LOG << "Full archive manager not opened in " << context.Dir.BaseName() << Endl;
            return false;
        }
        if (!mngr && !TDiskFAManager::Check(context.Dir.PathName(), ComponentConfig.GetActiveLayersFinal(), ComponentConfig)) {
            ERROR_LOG << "Full archive manager check fail in " << context.Dir.BaseName() << Endl;
            return false;
        }
    }
    return true;
}

void TArchiveDataNormalizer::Fix(const NRTYServer::TNormalizerContext& context, const THolder<TFileMap>&) const {
    {
        AssertCorrectIndex(!Config.IsReadOnly, "index is broken and cannot be repaired in read-only mode");
        TDiskFAManager* mngr = const_cast<TDiskFAManager*>(context.Managers.GetManager<TDiskFAManager>(FULL_ARCHIVE_COMPONENT_NAME));
        THolder<TDiskFAManager> mngrHolder;
        if (!mngr) {
            mngrHolder.Reset(new TDiskFAManager(context.Dir.PathName(), 0, Config, 0, ComponentConfig.GetActiveLayersFinal(), false, false, false));
            mngr = mngrHolder.Get();
        }
        AssertCorrectIndex(mngr->Repair(), "cannot repair full archive");
        AssertCorrectIndex(mngr->Open(), "cannot open repaired full archive");
    }
}
