import { ux } from '@oclif/core/ux';
import { anykey } from './any-key.js';
import * as color from './colors.js';
export async function openUrl(url, browser, action, dependencies) {
    if (!dependencies) {
        const openModule = await import('open');
        dependencies = {
            anykey,
            urlOpener: openModule.default,
        };
    }
    let browserErrorShown = false;
    const showBrowserError = (browser) => {
        if (browserErrorShown)
            return;
        ux.warn(`We can't open ${browser ?? 'your default'} browser.`
            + ` Use a different browser or visit ${color.info(url)}${action ? ` to ${action}` : ''}.`);
        browserErrorShown = true;
    };
    ux.stdout(`Opening ${color.info(url)} in ${browser ?? 'your default'} browser…`);
    try {
        await dependencies.anykey(`Press any key to open up the browser${action ? ` to ${action}` : ''}, or ${color.warning('q')} to exit`);
    }
    catch (error) {
        const { message, oclif } = error;
        ux.error(message, { exit: oclif?.exit || 1 });
    }
    const cp = await dependencies.urlOpener(url, { wait: false, ...(browser ? { app: { name: browser } } : {}) });
    cp.on('error', (err) => {
        ux.warn(err);
        showBrowserError(browser);
    });
    cp.on('close', (code) => {
        if (code !== 0)
            showBrowserError(browser);
    });
}
