"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;
};
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;
    }
    async executeActionWithLock(action, lockFilePath, lockOpts) {
        const releaseFunc = await this.lock(lockFilePath, lockOpts);
        try {
            const result = await action();
            return result;
        }
        finally {
            releaseFunc();
        }
    }
    async lock(lockFilePath, lockOpts) {
        const { filePath, fileOpts } = this.getLockFileSettings(lockFilePath, lockOpts);
        for (const pathToClean of this.getPathsForCleanupAction(filePath)) {
            await this.$cleanupService.addCleanupDeleteAction(pathToClean);
        }
        this.$fs.writeFile(filePath, "");
        try {
            const releaseFunc = await lockfile.lock(filePath, fileOpts);
            return async () => {
                await releaseFunc();
                await this.cleanLock(filePath);
            };
        }
        catch (err) {
            throw new Error(`Timeout while waiting for lock "${filePath}"`);
        }
    }
    async unlock(lockFilePath) {
        const { filePath } = this.getLockFileSettings(lockFilePath);
        lockfile.unlockSync(filePath);
        await this.cleanLock(filePath);
    }
    async cleanLock(lockPath) {
        this.$fs.deleteFile(lockPath);
        for (const filePath of this.getPathsForCleanupAction(lockPath)) {
            await 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;
    }
}
exports.LockService = LockService;
__decorate([
    (0, decorators_1.cache)()
], LockService.prototype, "defaultLockFilePath", null);
yok_1.injector.register("lockService", LockService);
yok_1.injector.register("lockfile", LockService);
