"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FilesHashService = void 0;
const helpers_1 = require("../common/helpers");
const constants_1 = require("../common/constants");
const constants_2 = require("../constants");
const path = require("path");
const _ = require("lodash");
const yok_1 = require("../common/yok");
class FilesHashService {
    constructor($fs, $logger, $options) {
        this.$fs = $fs;
        this.$logger = $logger;
        this.$options = $options;
    }
    async generateHashes(files) {
        const result = {};
        const action = async (file) => {
            try {
                const isFile = this.$fs.getFsStats(file).isFile();
                if (isFile) {
                    result[file] = await this.$fs.getFileShasum(file);
                }
            }
            catch (err) {
                this.$logger.trace(`Unable to generate hash for file ${file}. Error is: ${err}`);
            }
        };
        await (0, helpers_1.executeActionByChunks)(files, constants_1.DEFAULT_CHUNK_SIZE, action);
        return result;
    }
    async generateHashesForProject(platformData) {
        const appFilesPath = path.join(platformData.appDestinationDirectoryPath, this.$options.hostProjectModuleName);
        const files = this.$fs.enumerateFilesInDirectorySync(appFilesPath);
        const hashes = await this.generateHashes(files);
        return hashes;
    }
    async saveHashesForProject(platformData, hashesFileDirectory) {
        const hashes = await this.generateHashesForProject(platformData);
        this.saveHashes(hashes, hashesFileDirectory);
        return hashes;
    }
    async getChanges(files, oldHashes) {
        const newHashes = await this.generateHashes(files);
        return this.getChangesInShasums(oldHashes, newHashes);
    }
    hasChangesInShasums(oldHashes, newHashes) {
        return !!_.keys(this.getChangesInShasums(oldHashes, newHashes)).length;
    }
    saveHashes(hashes, hashesFileDirectory) {
        const hashesFilePath = path.join(hashesFileDirectory, constants_2.HASHES_FILE_NAME);
        this.$fs.writeJson(hashesFilePath, hashes);
    }
    getChangesInShasums(oldHashes, newHashes) {
        const addedFileHashes = _.omitBy(newHashes, (hash, pathToFile) => !!oldHashes[pathToFile] && oldHashes[pathToFile] === hash);
        const removedFileHashes = _.omitBy(oldHashes, (hash, pathToFile) => !!newHashes[pathToFile] && newHashes[pathToFile] === hash);
        const result = {};
        _.extend(result, addedFileHashes, removedFileHashes);
        return result;
    }
}
exports.FilesHashService = FilesHashService;
yok_1.injector.register("filesHashService", FilesHashService);
