"use strict";
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);
        }
    }
    async begin(name) {
        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);
        });
        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);
