/**
 * Utilities for working with `osascript` which runs AppleScript on Macs
 */
'use strict';
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());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const exec_async_1 = __importDefault(require("exec-async"));
const path_1 = __importDefault(require("path"));
const spawn_async_1 = __importDefault(require("@expo/spawn-async"));
const util_1 = __importDefault(require("util"));
function osascriptArgs(script) {
    if (!util_1.default.isArray(script)) {
        script = [script];
    }
    let args = [];
    for (let line of script) {
        args.push('-e');
        args.push(line);
    }
    return args;
}
function osascriptExecAsync(script, opts) {
    return __awaiter(this, void 0, void 0, function* () {
        return yield exec_async_1.default('osascript', osascriptArgs(script), Object.assign({ stdio: 'inherit' }, opts));
    });
}
exports.execAsync = osascriptExecAsync;
function osascriptSpawnAsync(script, opts) {
    return __awaiter(this, void 0, void 0, function* () {
        return yield spawn_async_1.default('osascript', osascriptArgs(script), opts);
    });
}
exports.spawnAsync = osascriptSpawnAsync;
function isAppRunningAsync(appName) {
    return __awaiter(this, void 0, void 0, function* () {
        let zeroMeansNo = (yield osascriptExecAsync('tell app "System Events" to count processes whose name is ' + JSON.stringify(appName))).trim();
        return zeroMeansNo !== '0';
    });
}
exports.isAppRunningAsync = isAppRunningAsync;
function safeIdOfAppAsync(appName) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            return (yield osascriptExecAsync('id of app ' + JSON.stringify(appName))).trim();
        }
        catch (e) {
            return null;
        }
    });
}
exports.safeIdOfAppAsync = safeIdOfAppAsync;
function openFinderToFolderAsync(dir, activate = true) {
    return __awaiter(this, void 0, void 0, function* () {
        yield osascriptSpawnAsync([
            'tell application "Finder"',
            'open POSIX file ' + JSON.stringify(dir),
            (activate && 'activate') || '',
            'end tell',
        ]);
    });
}
exports.openFinderToFolderAsync = openFinderToFolderAsync;
function openInAppAsync(appName, pth) {
    return __awaiter(this, void 0, void 0, function* () {
        let cmd = 'tell app ' + JSON.stringify(appName) + ' to open ' + JSON.stringify(path_1.default.resolve(pth));
        // console.log("cmd=", cmd);
        return yield osascriptSpawnAsync(cmd);
    });
}
exports.openInAppAsync = openInAppAsync;
function chooseAppAsync(listOfAppNames) {
    return __awaiter(this, void 0, void 0, function* () {
        let runningAwaitables = [];
        let appIdAwaitables = [];
        for (let appName of listOfAppNames) {
            runningAwaitables.push(isAppRunningAsync(appName));
            appIdAwaitables.push(safeIdOfAppAsync(appName));
        }
        let running = yield Promise.all(runningAwaitables);
        let appIds = yield Promise.all(appIdAwaitables);
        let i;
        for (i = 0; i < listOfAppNames.length; i++) {
            if (running[i]) {
                return listOfAppNames[i];
            }
        }
        for (i = 0; i < listOfAppNames.length; i++) {
            if (appIds[i]) {
                return listOfAppNames[i];
            }
        }
        return null;
    });
}
exports.chooseAppAsync = chooseAppAsync;
function chooseEditorAppAsync(preferredEditor) {
    return __awaiter(this, void 0, void 0, function* () {
        if (preferredEditor) {
            // Make sure this editor exists
            let appId = yield safeIdOfAppAsync(preferredEditor);
            if (appId) {
                return preferredEditor;
            }
            else {
                console.warn(`Your preferred editor (${preferredEditor}) isn't installed on this computer.`);
            }
        }
        let editorsToTry = [
            'Visual Studio Code',
            'Atom',
            'Sublime Text',
            'TextMate',
            'TextWrangler',
            'Visual Studio Code',
            'Brackets',
            'SubEthaEdit',
            'BBEdit',
            'Textastic',
            'UltraEdit',
            'MacVim',
            'CodeRunner 2',
            'CodeRunner',
            'TextEdit',
        ];
        return yield chooseAppAsync(editorsToTry);
    });
}
exports.chooseEditorAppAsync = chooseEditorAppAsync;
function chooseTerminalAppAsync() {
    return __awaiter(this, void 0, void 0, function* () {
        return yield chooseAppAsync([
            'iTerm 3',
            'iTerm 2',
            'iTerm',
            'HyperTerm',
            // 'Cathode',
            // 'Terminator',
            // 'MacTerm',
            'Terminal',
        ]);
    });
}
exports.chooseTerminalAppAsync = chooseTerminalAppAsync;
function openInEditorAsync(pth, preferredEditor) {
    return __awaiter(this, void 0, void 0, function* () {
        let appName = yield chooseEditorAppAsync(preferredEditor);
        if (!appName) {
            throw new Error('No editor found.');
        }
        console.log('Will open in ' + appName + ' -- ' + pth);
        return yield openInAppAsync(appName, pth);
    });
}
exports.openInEditorAsync = openInEditorAsync;
function openItermToSpecificFolderAsync(dir) {
    return __awaiter(this, void 0, void 0, function* () {
        return yield osascriptSpawnAsync([
            'tell application "iTerm"',
            'make new terminal',
            'tell the first terminal',
            'activate current session',
            'launch session "Default Session"',
            'tell the last session',
            'write text "cd ' + util_1.default.inspect(dir) + ' && clear"',
            // 'write text "clear"',
            'end tell',
            'end tell',
            'end tell',
        ]);
        // exec("osascript -e 'tell application \"iTerm\"' -e 'make new terminal' -e 'tell the first terminal' -e 'activate current session' -e 'launch session \"Default Session\"' -e 'tell the last session' -e 'write text \"cd #{value}\"' -e 'write text \"clear\"' -e 'end tell' -e 'end tell' -e 'end tell' > /dev/null 2>&1")
    });
}
exports.openItermToSpecificFolderAsync = openItermToSpecificFolderAsync;
function openTerminalToSpecificFolderAsync(dir, inTab = false) {
    return __awaiter(this, void 0, void 0, function* () {
        if (inTab) {
            return yield osascriptSpawnAsync([
                'tell application "terminal"',
                'tell application "System Events" to tell process "terminal" to keystroke "t" using command down',
                'do script with command "cd ' +
                    util_1.default.inspect(dir) +
                    ' && clear" in selected tab of the front window',
                'end tell',
            ]);
        }
        else {
            return yield osascriptSpawnAsync([
                'tell application "terminal"',
                'do script "cd ' + util_1.default.inspect(dir) + ' && clear"',
                'end tell',
                'tell application "terminal" to activate',
            ]);
        }
    });
}
exports.openTerminalToSpecificFolderAsync = openTerminalToSpecificFolderAsync;
function openFolderInTerminalAppAsync(dir, inTab = false) {
    return __awaiter(this, void 0, void 0, function* () {
        let program = yield chooseTerminalAppAsync();
        switch (program) {
            case 'iTerm':
                return yield openItermToSpecificFolderAsync(dir);
            case 'Terminal':
            default:
                return yield openTerminalToSpecificFolderAsync(dir, inTab);
        }
    });
}
exports.openFolderInTerminalAppAsync = openFolderInTerminalAppAsync;
//# sourceMappingURL=index.js.map