const ChildProcess = require('child_process');

// Spawn a command and invoke the callback when it completes with an error
// and the output from standard out.
//
// * `command`    The underlying OS command {String} to execute.
// * `args` (optional) The {Array} with arguments to be passed to command.
// * `callback` (optional) The {Function} to call after the command has run. It will be invoked with arguments:
//   * `error` (optional) An {Error} object returned by the command, `null` if no error was thrown.
//     * `code` Error code returned by the command.
//     * `stdout`  The {String} output text generated by the command.
//   * `stdout`  The {String} output text generated by the command.
exports.spawn = function(command, args, callback) {
  let error;
  let spawnedProcess;
  let stdout = '';

  try {
    spawnedProcess = ChildProcess.spawn(command, args);
  } catch (error) {
    process.nextTick(() => callback && callback(error, stdout));
    return;
  }

  spawnedProcess.stdout.on('data', data => {
    stdout += data;
  });
  spawnedProcess.on('error', processError => {
    error = processError;
  });
  spawnedProcess.on('close', (code, signal) => {
    if (!error && code !== 0) {
      error = new Error(`Command failed: ${signal != null ? signal : code}`);
    }

    if (error) {
      if (error.code == null) error.code = code;
      if (error.stdout == null) error.stdout = stdout;
    }

    callback && callback(error, stdout);
  });

  // This is necessary if using Powershell 2 on Windows 7 to get the events to raise
  // http://stackoverflow.com/questions/9155289/calling-powershell-from-nodejs
  return spawnedProcess.stdin.end();
};
