"use strict";
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 });
const choki = require("chokidar");
const path = require("path");
const os = require("os");
const _ = require("lodash");
const yok_1 = require("../yok");
class CancellationService {
    constructor($fs, $logger, $hostInfo) {
        this.$fs = $fs;
        this.$logger = $logger;
        this.$hostInfo = $hostInfo;
        this.watches = {};
        if (this.$hostInfo.isWindows) {
            this.$fs.createDirectory(CancellationService.killSwitchDir);
        }
    }
    begin(name) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.$hostInfo.isWindows) {
                return;
            }
            const triggerFile = CancellationService.makeKillSwitchFileName(name);
            if (!this.$fs.exists(triggerFile)) {
                this.$fs.writeFile(triggerFile, "");
            }
            this.$logger.trace("Starting watch on killswitch %s", triggerFile);
            const watcher = choki
                .watch(triggerFile, { ignoreInitial: true })
                .on("unlink", (filePath) => {
                this.$logger.info(`Exiting process as the file ${filePath} has been deleted. Probably reinstalling CLI while there's a working instance.`);
                process.exit(132 /* ErrorCodes.DELETED_KILL_FILE */);
            });
            if (watcher) {
                this.watches[name] = watcher;
            }
        });
    }
    end(name) {
        const watcher = this.watches[name];
        if (watcher) {
            delete this.watches[name];
            watcher.close().then().catch();
        }
    }
    dispose() {
        _(this.watches)
            .keys()
            .each((name) => this.end(name));
    }
    static get killSwitchDir() {
        return path.join(os.tmpdir(), process.env.SUDO_USER || process.env.USER || process.env.USERNAME || "", "KillSwitches");
    }
    static makeKillSwitchFileName(name) {
        return path.join(CancellationService.killSwitchDir, name);
    }
}
yok_1.injector.register("cancellation", CancellationService);
//# sourceMappingURL=cancellation.js.map