#include "name_normalizer.h"
#include "globals.h"

const char* TArchiveNamesNormalizer::Name() const {
    return "FANamesNormalizer";
}

bool TArchiveNamesNormalizer::AllRight(const NRTYServer::TNormalizerContext& context, const THolder<TFileMap>& /*indexFrq*/) const {
    const TFsPath directory(context.Dir.PathName());

    TVector<TString> children;
    directory.ListNames(children);
    for (auto&& child : children) {
        if (child.StartsWith(OLD_FULL_ARC_FILE_NAME_PREFIX)) {
            WARNING_LOG << "File " << child << " has old prefix" << Endl;
            return false;
        }
    }

    return true;
}

void TArchiveNamesNormalizer::Fix(const NRTYServer::TNormalizerContext& context, const THolder<TFileMap>& /*indexFrq*/) const {
    NRTYServer::NFullArchive::NormalizeNames(context.Dir.PathName());
}

void NRTYServer::NFullArchive::NormalizeNames(const TFsPath& directory) {
    TVector<TFsPath> children;
    directory.List(children);

    for (auto&& child : children) {
        const TString& name = child.Basename();
        if (name.StartsWith(OLD_FULL_ARC_FILE_NAME_PREFIX)) {
            INFO_LOG << "Correcting name for " << child << Endl;
            const TString& suffix = {name.data() + OLD_FULL_ARC_FILE_NAME_PREFIX.size(), name.end()};
            const TFsPath target = directory / (FULL_ARC_FILE_NAME_PREFIX + suffix);
            child.RenameTo(target);
        }
    }
}
