"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.openBrowser = void 0;
/**
 * The following code is modified based on source found in
 * https://github.com/facebook/create-react-app
 *
 * MIT Licensed
 * Copyright (c) 2015-present, Facebook, Inc.
 * https://github.com/facebook/create-react-app/blob/master/LICENSE
 */
const child_process_1 = require("child_process");
const path_1 = require("path");
const open_1 = __importDefault(require("../compiled/open"));
const logger_1 = require("./logger");
const supportedChromiumBrowsers = [
    'Google Chrome Canary',
    'Google Chrome Dev',
    'Google Chrome Beta',
    'Google Chrome',
    'Microsoft Edge',
    'Brave Browser',
    'Vivaldi',
    'Chromium',
];
async function openBrowser(url) {
    // If we're on OS X, the user hasn't specifically
    // requested a different browser, we can try opening
    // a Chromium browser with AppleScript. This lets us reuse an
    // existing tab when possible instead of creating a new one.
    const shouldTryOpenChromeWithAppleScript = process.platform === 'darwin';
    if (shouldTryOpenChromeWithAppleScript) {
        try {
            const ps = (0, child_process_1.execSync)('ps cax').toString();
            const openedBrowser = supportedChromiumBrowsers.find(b => ps.includes(b));
            if (openedBrowser) {
                // Try to reuse existing tab with AppleScript
                (0, child_process_1.execSync)(`osascript openChrome.applescript "${encodeURI(url)}" "${openedBrowser}"`, {
                    stdio: 'ignore',
                    cwd: (0, path_1.join)(__dirname, '../static'),
                });
                return true;
            }
        }
        catch (err) {
            logger_1.logger.error('Failed to open start URL with apple script:', JSON.stringify(err));
            return false;
        }
    }
    // Fallback to open
    // (It will always open new tab)
    try {
        await (0, open_1.default)(url);
        return true;
    }
    catch (err) {
        logger_1.logger.error('Failed to open start URL:', JSON.stringify(err));
        return false;
    }
}
exports.openBrowser = openBrowser;
