"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) {
    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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const path = require("path");
const decorators_1 = require("../common/decorators");
class CleanupService {
    constructor($options, $staticConfig, $childProcess) {
        this.$staticConfig = $staticConfig;
        this.$childProcess = $childProcess;
        this.shouldDispose = true;
        this.pathToCleanupLogFile = $options.cleanupLogFile;
    }
    addCleanupCommand(commandInfo) {
        return __awaiter(this, void 0, void 0, function* () {
            const cleanupProcess = yield this.getCleanupProcess();
            cleanupProcess.send({ messageType: "AddCleanCommand", commandInfo });
        });
    }
    removeCleanupCommand(commandInfo) {
        return __awaiter(this, void 0, void 0, function* () {
            const cleanupProcess = yield this.getCleanupProcess();
            cleanupProcess.send({ messageType: "RemoveCleanCommand", commandInfo });
        });
    }
    addCleanupDeleteAction(filePath) {
        return __awaiter(this, void 0, void 0, function* () {
            const cleanupProcess = yield this.getCleanupProcess();
            cleanupProcess.send({ messageType: "AddDeleteFileAction", filePath });
        });
    }
    removeCleanupDeleteAction(filePath) {
        return __awaiter(this, void 0, void 0, function* () {
            const cleanupProcess = yield this.getCleanupProcess();
            cleanupProcess.send({ messageType: "RemoveDeleteFileAction", filePath });
        });
    }
    addCleanupJS(jsCommand) {
        return __awaiter(this, void 0, void 0, function* () {
            const cleanupProcess = yield this.getCleanupProcess();
            cleanupProcess.send({ messageType: "AddJSFileToRequire", jsCommand });
        });
    }
    removeCleanupJS(jsCommand) {
        return __awaiter(this, void 0, void 0, function* () {
            const cleanupProcess = yield this.getCleanupProcess();
            cleanupProcess.send({ messageType: "RemoveJSFileToRequire", jsCommand });
        });
    }
    setCleanupLogFile(filePath) {
        this.pathToCleanupLogFile = filePath;
    }
    dispose() {
        if (this.cleanupProcess && this.shouldDispose) {
            this.cleanupProcess.disconnect();
        }
    }
    setShouldDispose(shouldDispose) {
        this.shouldDispose = shouldDispose;
    }
    getCleanupProcess() {
        return new Promise((resolve, reject) => {
            const cleanupProcessArgs = this.getCleanupProcessArgs();
            const cleanupProcess = this.$childProcess.spawn(process.execPath, cleanupProcessArgs, {
                stdio: ["ignore", "ignore", "ignore", "ipc"],
                detached: true
            });
            cleanupProcess.unref();
            let isSettled = false;
            const timeoutId = setTimeout(() => {
                if (!isSettled) {
                    reject(new Error("Unable to start Cleanup process."));
                }
            }, CleanupService.CLEANUP_PROCESS_START_TIMEOUT);
            cleanupProcess.on("error", (err) => {
                clearTimeout(timeoutId);
                if (!isSettled) {
                    isSettled = true;
                    reject(err);
                }
            });
            cleanupProcess.on("message", (data) => {
                if (data === "ProcessReadyToReceive") {
                    clearTimeout(timeoutId);
                    if (!isSettled) {
                        isSettled = true;
                        this.cleanupProcess = cleanupProcess;
                        resolve(cleanupProcess);
                    }
                }
            });
        });
    }
    getCleanupProcessArgs() {
        const cleanupProcessArgs = [
            path.join(__dirname, "..", "detached-processes", "cleanup-process.js"),
            this.$staticConfig.PATH_TO_BOOTSTRAP,
        ];
        if (this.pathToCleanupLogFile) {
            cleanupProcessArgs.push(path.resolve(this.pathToCleanupLogFile));
        }
        return cleanupProcessArgs;
    }
}
CleanupService.CLEANUP_PROCESS_START_TIMEOUT = 10 * 1000;
__decorate([
    decorators_1.exported("cleanupService")
], CleanupService.prototype, "setCleanupLogFile", null);
__decorate([
    decorators_1.cache()
], CleanupService.prototype, "getCleanupProcess", null);
exports.CleanupService = CleanupService;
$injector.register("cleanupService", CleanupService);
