"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
exports.__esModule = true;
var path_1 = __importDefault(require("path"));
var child_process_1 = __importDefault(require("child_process"));
var fs_1 = require("fs");
var is_wsl_1 = __importDefault(require("is-wsl"));
var is_docker_1 = __importDefault(require("is-docker"));
var define_lazy_prop_1 = __importDefault(require("define-lazy-prop"));
var localXdgOpenPath = path_1["default"].join(__dirname, 'xdg-open');
var platform = process.platform, arch = process.arch;
var hasContainerEnv = function () { return __awaiter(void 0, void 0, void 0, function () {
    var _a;
    return __generator(this, function (_b) {
        switch (_b.label) {
            case 0:
                _b.trys.push([0, 2, , 3]);
                return [4, fs_1.promises.stat('/run/.containerenv')];
            case 1:
                _b.sent();
                return [2, true];
            case 2:
                _a = _b.sent();
                return [2, false];
            case 3: return [2];
        }
    });
}); };
var cachedResult;
function isInsideContainer() {
    if (cachedResult === undefined) {
        cachedResult = hasContainerEnv() || (0, is_docker_1["default"])();
    }
    return cachedResult;
}
var getWslDrivesMountPoint = (function () {
    var defaultMountPoint = '/mnt/';
    var mountPoint;
    return function () {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            var configFilePath, isConfigFileExists, _b, configContent, configMountPoint;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        if (mountPoint) {
                            return [2, mountPoint];
                        }
                        configFilePath = '/etc/wsl.conf';
                        isConfigFileExists = false;
                        _c.label = 1;
                    case 1:
                        _c.trys.push([1, 3, , 4]);
                        return [4, fs_1.promises.access(configFilePath, fs_1.constants.F_OK)];
                    case 2:
                        _c.sent();
                        isConfigFileExists = true;
                        return [3, 4];
                    case 3:
                        _b = _c.sent();
                        return [3, 4];
                    case 4:
                        if (!isConfigFileExists) {
                            return [2, defaultMountPoint];
                        }
                        return [4, fs_1.promises.readFile(configFilePath, { encoding: 'utf8' })];
                    case 5:
                        configContent = _c.sent();
                        configMountPoint = /(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent);
                        if (!configMountPoint) {
                            return [2, defaultMountPoint];
                        }
                        mountPoint = (_a = configMountPoint.groups) === null || _a === void 0 ? void 0 : _a.mountPoint.trim();
                        mountPoint = (mountPoint === null || mountPoint === void 0 ? void 0 : mountPoint.endsWith('/')) ? mountPoint : "".concat(mountPoint, "/");
                        return [2, mountPoint];
                }
            });
        });
    };
})();
var pTryEach = function (array, mapper) { return __awaiter(void 0, void 0, void 0, function () {
    var latestError, _i, array_1, item, error_1;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0:
                _i = 0, array_1 = array;
                _a.label = 1;
            case 1:
                if (!(_i < array_1.length)) return [3, 6];
                item = array_1[_i];
                _a.label = 2;
            case 2:
                _a.trys.push([2, 4, , 5]);
                return [4, mapper(item)];
            case 3: return [2, _a.sent()];
            case 4:
                error_1 = _a.sent();
                latestError = error_1;
                return [3, 5];
            case 5:
                _i++;
                return [3, 1];
            case 6: throw latestError;
        }
    });
}); };
var baseOpen = function (options) { return __awaiter(void 0, void 0, void 0, function () {
    var _a, app, _b, appArguments, command, cliArguments, childProcessOptions, mountPoint, encodedArguments, isBundled, exeLocalXdgOpen, _c, useSystemXdgOpen, subprocess;
    return __generator(this, function (_d) {
        switch (_d.label) {
            case 0:
                options = __assign({ wait: false, background: false, newInstance: false, allowNonzeroExitCode: false }, options);
                if (Array.isArray(options.app)) {
                    return [2, pTryEach(options.app, function (singleApp) { return baseOpen(__assign(__assign({}, options), { app: singleApp })); })];
                }
                _a = options.app || {}, app = _a.name, _b = _a.arguments, appArguments = _b === void 0 ? [] : _b;
                appArguments = __spreadArray([], appArguments, true);
                if (Array.isArray(app)) {
                    return [2, pTryEach(app, function (appName) { return baseOpen(__assign(__assign({}, options), { app: {
                                name: appName,
                                arguments: appArguments
                            } })); })];
                }
                cliArguments = [];
                childProcessOptions = {};
                if (!(platform === 'darwin')) return [3, 1];
                command = 'open';
                if (options.wait) {
                    cliArguments.push('--wait-apps');
                }
                if (options.background) {
                    cliArguments.push('--background');
                }
                if (options.newInstance) {
                    cliArguments.push('--new');
                }
                if (app) {
                    cliArguments.push('-a', app);
                }
                return [3, 10];
            case 1:
                if (!(platform === 'win32' || (is_wsl_1["default"] && !isInsideContainer() && !app))) return [3, 3];
                return [4, getWslDrivesMountPoint()];
            case 2:
                mountPoint = _d.sent();
                command = is_wsl_1["default"] ?
                    "".concat(mountPoint, "c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe") :
                    "".concat(process.env.SYSTEMROOT, "\\System32\\WindowsPowerShell\\v1.0\\powershell");
                cliArguments.push('-NoProfile', '-NonInteractive', '–ExecutionPolicy', 'Bypass', '-EncodedCommand');
                if (!is_wsl_1["default"]) {
                    childProcessOptions.windowsVerbatimArguments = true;
                }
                encodedArguments = ['Start'];
                if (options.wait) {
                    encodedArguments.push('-Wait');
                }
                if (app) {
                    encodedArguments.push("\"`\"".concat(app, "`\"\""), '-ArgumentList');
                    if (options.target) {
                        appArguments.unshift(options.target);
                    }
                }
                else if (options.target) {
                    encodedArguments.push("\"".concat(options.target, "\""));
                }
                if (appArguments.length > 0) {
                    appArguments = appArguments.map(function (arg) { return "\"`\"".concat(arg, "`\"\""); });
                    encodedArguments.push(appArguments.join(','));
                }
                options.target = Buffer.from(encodedArguments.join(' '), 'utf16le').toString('base64');
                return [3, 10];
            case 3:
                if (!app) return [3, 4];
                command = app;
                return [3, 9];
            case 4:
                isBundled = !__dirname || __dirname === '/';
                exeLocalXdgOpen = false;
                _d.label = 5;
            case 5:
                _d.trys.push([5, 7, , 8]);
                return [4, fs_1.promises.access(localXdgOpenPath, fs_1.constants.X_OK)];
            case 6:
                _d.sent();
                exeLocalXdgOpen = true;
                return [3, 8];
            case 7:
                _c = _d.sent();
                return [3, 8];
            case 8:
                useSystemXdgOpen = process.versions.electron ||
                    platform === 'android' || isBundled || !exeLocalXdgOpen;
                command = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath;
                _d.label = 9;
            case 9:
                if (appArguments.length > 0) {
                    cliArguments.push.apply(cliArguments, appArguments);
                }
                if (!options.wait) {
                    childProcessOptions.stdio = 'ignore';
                    childProcessOptions.detached = true;
                }
                _d.label = 10;
            case 10:
                if (options.target) {
                    cliArguments.push(options.target);
                }
                if (platform === 'darwin' && appArguments.length > 0) {
                    cliArguments.push.apply(cliArguments, __spreadArray(['--args'], appArguments, false));
                }
                subprocess = child_process_1["default"].spawn(command, cliArguments, childProcessOptions);
                if (options.wait) {
                    return [2, new Promise(function (resolve, reject) {
                            subprocess.once('error', reject);
                            subprocess.once('close', function (exitCode) {
                                if (!options.allowNonzeroExitCode && exitCode > 0) {
                                    reject(new Error("Exited with code ".concat(exitCode)));
                                    return;
                                }
                                resolve(subprocess);
                            });
                        })];
                }
                subprocess.unref();
                return [2, subprocess];
        }
    });
}); };
var open = function (target, options) {
    if (options === void 0) { options = {}; }
    if (typeof target !== 'string') {
        throw new TypeError('Expected a `target`');
    }
    return baseOpen(__assign(__assign({}, options), { target: target }));
};
var openApp = function (name, options) {
    if (typeof name !== 'string') {
        throw new TypeError('Expected a `name`');
    }
    var _a = (options || {}).arguments, appArguments = _a === void 0 ? [] : _a;
    if (appArguments !== undefined && appArguments !== null && !Array.isArray(appArguments)) {
        throw new TypeError('Expected `appArguments` as Array type');
    }
    return baseOpen(__assign(__assign({}, options), { app: {
            name: name,
            arguments: appArguments
        } }));
};
function detectArchBinary(binary) {
    if (typeof binary === 'string' || Array.isArray(binary)) {
        return binary;
    }
    var _a = binary, _b = arch, archBinary = _a[_b];
    if (!archBinary) {
        throw new Error("".concat(arch, " is not supported"));
    }
    return archBinary;
}
function detectPlatformBinary(_a, _b) {
    var _c = platform, platformBinary = _a[_c];
    var wsl = _b.wsl;
    if (wsl && is_wsl_1["default"]) {
        return detectArchBinary(wsl);
    }
    if (!platformBinary) {
        throw new Error("".concat(platform, " is not supported"));
    }
    return detectArchBinary(platformBinary);
}
var apps = {};
(0, define_lazy_prop_1["default"])(apps, 'chrome', function () { return detectPlatformBinary({
    darwin: 'google chrome',
    win32: 'chrome',
    linux: ['google-chrome', 'google-chrome-stable', 'chromium']
}, {
    wsl: {
        ia32: '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe',
        x64: ['/mnt/c/Program Files/Google/Chrome/Application/chrome.exe', '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe']
    }
}); });
(0, define_lazy_prop_1["default"])(apps, 'firefox', function () { return detectPlatformBinary({
    darwin: 'firefox',
    win32: 'C:\\Program Files\\Mozilla Firefox\\firefox.exe',
    linux: 'firefox'
}, {
    wsl: '/mnt/c/Program Files/Mozilla Firefox/firefox.exe'
}); });
(0, define_lazy_prop_1["default"])(apps, 'edge', function () { return detectPlatformBinary({
    darwin: 'microsoft edge',
    win32: 'msedge',
    linux: ['microsoft-edge', 'microsoft-edge-dev']
}, {
    wsl: '/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'
}); });
open.apps = apps;
open.openApp = openApp;
exports["default"] = open;
