'use strict';

var opn = require('opn');

function getChromeAppName() {
  switch (process.platform) {
    case 'darwin':
      return 'google chrome';
    case 'win32':
      return 'chrome';
    default:
      return 'google-chrome';
  }
}
var pendingList = [];
var pending = false;
exports.launchChrome = function (url, remoteDebugPort, wait, callback) {
  if (!pending) {
    pending = true;
    url = url.replace(/[&*]/g, '\\&');
    var args = [getChromeAppName()];
    if (remoteDebugPort > 0) {
      args.push('-remote-debugging-port=' + remoteDebugPort);
    }
    opn(url, {
      app: args,
      wait: !!wait
    }).then(function (cp) {
      cp.once('close', function (e) {
        callback && callback(null);
        pending = false;
        if (pendingList.length > 0) {
          pendingList.shift()();
        }
      });
      cp.once('error', function (err) {
        pending = false;
        callback && callback(err);
      });
    });
  } else {
    pendingList.push(function () {
      exports.launchChrome(url, remoteDebugPort, wait, callback);
    });
  }
};
exports.launchNewChrome = function (url, args) {};