#include "files_normalizer.h"
#include "component.h"
#include "config.h"
#include "globals.h"

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

const char* TArchiveFilesNormalizer::Name() const {
    return "FAFilesNormalizer";
}

bool TArchiveFilesNormalizer::AllRight(const NRTYServer::TNormalizerContext& context, const THolder<TFileMap>&) const {
    return CheckOrFixFiles(context, false);
}

void TArchiveFilesNormalizer::Fix(const NRTYServer::TNormalizerContext& context, const THolder<TFileMap>&) const {
    CheckOrFixFiles(context, true);
}

bool TArchiveFilesNormalizer::CheckOrFixFiles(const NRTYServer::TNormalizerContext& context, bool fix) const {
    const auto& activeLayers = ComponentConfig.GetActiveLayersFinal();

    TFsPath path(context.Dir.PathName());
    TVector<TFsPath> files;
    path.List(files);

    for (const auto& f : files) {
        if (f.GetName().StartsWith(FULL_ARC_FILE_NAME_PREFIX)) {
            size_t len = FULL_ARC_FILE_NAME_PREFIX.length();
            size_t pos = f.GetName().find('.', len);
            TString layer = f.GetName().substr(len, pos - len);
            if (!activeLayers.contains(layer)) {
                if (fix) {
                    NFs::Remove(f);
                } else {
                    ERROR_LOG << "there is not needed file " << f.GetPath() << Endl;
                    return false;
                }
            }
        }
    }
    return true;
}
