"use strict";
// open-or-focus-app.ts
Object.defineProperty(exports, "__esModule", { value: true });
exports.openOrFocus = openOrFocus;
var electron_1 = require("electron");
var child_process_1 = require("child_process");
var fs = require("fs");
function openOrFocus(folder, isUrl) {
    if (isUrl) {
        return electron_1.shell.openExternal(folder);
    }
    if (!fs.existsSync(folder)) {
        return Promise.reject(new Error("Path does not exist: ".concat(folder)));
    }
    if (process.platform === 'darwin') {
        return openOrFocusMac(folder);
    }
    if (process.platform === 'win32') {
        return openOrFocusWindows(folder);
    }
    return electron_1.shell.openPath(folder).then(function (errorMessage) {
        if (errorMessage) {
            throw new Error(errorMessage);
        }
    });
}
function openOrFocusMac(appPath) {
    return new Promise(function (resolve, reject) {
        (0, child_process_1.execFile)('open', [getMacAppBundlePath(appPath)], function (error) {
            if (error) {
                reject(error);
                return;
            }
            resolve();
        });
    });
}
function getMacAppBundlePath(inputPath) {
    var appIndex = inputPath.toLowerCase().indexOf('.app');
    return appIndex === -1 ? inputPath : inputPath.substring(0, appIndex + 4);
}
function openOrFocusWindows(appPath) {
    return new Promise(function (resolve, reject) {
        var script = getWindowsScript(appPath);
        (0, child_process_1.execFile)('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', script], function (error, stdout, stderr) {
            if (stdout) {
                console.log('openOrFocus stdout:', stdout);
            }
            if (stderr) {
                console.error('openOrFocus stderr:', stderr);
            }
            if (error) {
                reject(error);
                return;
            }
            resolve();
        });
    });
}
function getWindowsScript(appPath) {
    var safeAppPath = escapePowerShellString(appPath);
    return "\n$inputPath = '".concat(safeAppPath, "'\n$appName = [System.IO.Path]::GetFileNameWithoutExtension($inputPath)\n\n$proc = Get-Process -Name $appName -ErrorAction SilentlyContinue |\n  Where-Object { $_.MainWindowTitle -ne \"\" -and $_.MainWindowHandle -ne 0 } |\n  Select-Object -First 1\n\nif ($proc) {\n  Write-Output \"FOCUSING: $($proc.ProcessName), PID: $($proc.Id)\"\n\n  Add-Type @\"\nusing System;\nusing System.Runtime.InteropServices;\n\npublic class Win32 {\n  [DllImport(\"user32.dll\")]\n  public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);\n\n  [DllImport(\"user32.dll\")]\n  public static extern bool SetForegroundWindow(IntPtr hWnd);\n}\n\"@\n\n  # 9 = restore if minimized\n  [Win32]::ShowWindowAsync($proc.MainWindowHandle, 9) | Out-Null\n  Start-Sleep -Milliseconds 200\n\n  # 5 = show and activate\n  [Win32]::ShowWindowAsync($proc.MainWindowHandle, 5) | Out-Null\n  Start-Sleep -Milliseconds 200\n\n  $wshell = New-Object -ComObject WScript.Shell\n  $wshell.AppActivate($proc.Id) | Out-Null\n  Start-Sleep -Milliseconds 200\n\n  [Win32]::SetForegroundWindow($proc.MainWindowHandle) | Out-Null\n} else {\n  Write-Output \"STARTING: $inputPath\"\n  Start-Process -FilePath $inputPath\n}\n");
}
function escapePowerShellString(value) {
    return value.replace(/'/g, "''");
}
