"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LockService = void 0;
const lockfile = require("proper-lockfile");
const path = require("path");
const decorators_1 = require("../decorators");
const helpers_1 = require("../helpers");
const yok_1 = require("../yok");
const _ = require("lodash");
class LockService {
    get defaultLockFilePath() {
        return this.getAbsoluteLockFilePath("lockfile.lock");
    }
    getAbsoluteLockFilePath(relativeLockFilePath) {
        return path.join(this.$settingsService.getProfileDir(), relativeLockFilePath);
    }
    get defaultLockParams() {
        const lockParams = {
            retriesObj: { retries: 13, minTimeout: 100, maxTimeout: 1000, factor: 2 },
            stale: 10 * 1000,
            realpath: false,
        };
        return lockParams;
    }
    constructor($fs, $settingsService, $cleanupService) {
        this.$fs = $fs;
        this.$settingsService = $settingsService;
        this.$cleanupService = $cleanupService;
    }
    executeActionWithLock(action, lockFilePath, lockOpts) {
        return __awaiter(this, void 0, void 0, function* () {
            const releaseFunc = yield this.lock(lockFilePath, lockOpts);
            try {
                const result = yield action();
                return result;
            }
            finally {
                releaseFunc();
            }
        });
    }
    lock(lockFilePath, lockOpts) {
        return __awaiter(this, void 0, void 0, function* () {
            const { filePath, fileOpts } = this.getLockFileSettings(lockFilePath, lockOpts);
            for (const pathToClean of this.getPathsForCleanupAction(filePath)) {
                yield this.$cleanupService.addCleanupDeleteAction(pathToClean);
            }
            this.$fs.writeFile(filePath, "");
            try {
                const releaseFunc = yield lockfile.lock(filePath, fileOpts);
                return () => __awaiter(this, void 0, void 0, function* () {
                    yield releaseFunc();
                    yield this.cleanLock(filePath);
                });
            }
            catch (err) {
                throw new Error(`Timeout while waiting for lock "${filePath}"`);
            }
        });
    }
    unlock(lockFilePath) {
        return __awaiter(this, void 0, void 0, function* () {
            const { filePath } = this.getLockFileSettings(lockFilePath);
            lockfile.unlockSync(filePath);
            yield this.cleanLock(filePath);
        });
    }
    cleanLock(lockPath) {
        return __awaiter(this, void 0, void 0, function* () {
            this.$fs.deleteFile(lockPath);
            for (const filePath of this.getPathsForCleanupAction(lockPath)) {
                yield this.$cleanupService.removeCleanupDeleteAction(filePath);
            }
        });
    }
    getPathsForCleanupAction(lockPath) {
        return [lockPath, `${lockPath}.lock`];
    }
    getLockFileSettings(filePath, fileOpts) {
        if (filePath && !path.isAbsolute(filePath)) {
            filePath = this.getAbsoluteLockFilePath(filePath);
        }
        filePath = filePath || this.defaultLockFilePath;
        fileOpts = fileOpts
            ? _.assign({}, this.defaultLockParams, fileOpts)
            : this.defaultLockParams;
        fileOpts.retriesObj = fileOpts.retriesObj || {};
        if (fileOpts.retries) {
            fileOpts.retriesObj.retries = fileOpts.retries;
        }
        if (fileOpts.retryWait) {
            fileOpts.retriesObj.minTimeout = fileOpts.retriesObj.maxTimeout =
                fileOpts.retryWait;
        }
        fileOpts.retries = fileOpts.retriesObj;
        return {
            filePath: this.getShortFileLock(filePath),
            fileOpts,
        };
    }
    getShortFileLock(filePath) {
        const dirPath = path.dirname(filePath);
        const fileName = path.basename(filePath);
        const hashedFileName = (0, helpers_1.getHash)(fileName, { algorithm: "MD5" });
        filePath = path.join(dirPath, hashedFileName);
        return filePath;
    }
}
__decorate([
    (0, decorators_1.cache)()
], LockService.prototype, "defaultLockFilePath", null);
exports.LockService = LockService;
yok_1.injector.register("lockService", LockService);
yok_1.injector.register("lockfile", LockService);
