'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _commander = require('commander');

var _commander2 = _interopRequireDefault(_commander);

var _chalk = require('chalk');

var _chalk2 = _interopRequireDefault(_chalk);

var _stripAnsi = require('strip-ansi');

var _stripAnsi2 = _interopRequireDefault(_stripAnsi);

var _printTools = require('../utils/print-tools');

var _session = require('../utils/session');

var _session2 = _interopRequireDefault(_session);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

_commander2.default.Command.prototype.missingArgument = name => {
  (0, _printTools.echo)(`\nerror: ${_chalk2.default.cyan(`<${name}>`)} argument is ${_chalk2.default.red('required!')}`);
  _commander2.default.outputHelp();
  process.exit(1);
}; /* eslint no-underscore-dangle: "warn" */
/* eslint no-param-reassign: "warn" */


_commander2.default.Command.prototype.optionMissingArgument = (option, flag) => {
  if (flag) {
    (0, _printTools.echo)(`\nerror: missing ${_chalk2.default.cyan(`<${option.flags}>`)} argument, got ${_chalk2.default.red(flag)}`);
  }

  if (!flag) {
    (0, _printTools.echo)(`\nerror: ${_chalk2.default.cyan(`${option.flags}`)} argument is ${_chalk2.default.red('required!')}`);
  }

  _commander2.default.outputHelp();
  process.exit(1);
};

_commander2.default.Command.prototype.group = function (group) {
  this._group = group;
  return this;
};

// We are overriding this mainly to show separetly normal command and plugins
_commander2.default.Command.prototype.commandHelp = () => {
  if (!_commander2.default.commands.length) return '';

  // Search for plugins commands
  const plugins = Object.keys(_session2.default.getPluginsInstance().plugins);
  _commander2.default.commands.forEach(cmd => {
    if (!plugins.indexOf(cmd._name)) {
      // eslint-disable-next-line no-param-reassign
      cmd._plugin = true;
    }
  });

  function humanReadableArgName(arg) {
    const nameOutput = arg.name + (arg.variadic === true ? '...' : '');
    return arg.required ? `${_chalk2.default.white(`<${nameOutput}>`)}` : `${_chalk2.default.grey(`[${nameOutput}]`)}`;
  }

  function pad(str, width) {
    const len = Math.max(0, width - (0, _stripAnsi2.default)(str).length);
    return str + Array(len + 1).join(' ');
  }

  function printCmd(cmd) {
    const args = cmd._args.map(arg => humanReadableArgName(arg)).join(' ');

    return [[_chalk2.default.cyan(cmd._name), cmd._alias ? `|${cmd._alias}` : '', _chalk2.default.grey(cmd.options.length ? ' [options]' : ''), ' ', args].join(''), cmd._description];
  }

  const commandGroups = {};
  // Grouping commands
  _commander2.default.commands.filter(cmd => !cmd._noHelp && !cmd._plugin && cmd._name !== 'help').map(cmd => {
    let group = '';
    if (cmd._group) {
      group = cmd._group;
    } else {
      group = 'Other';
    }
    if (!commandGroups[group]) {
      commandGroups[group] = [];
    }
    commandGroups[group].push(printCmd(cmd));
    return printCmd(cmd);
  });

  // Plugins commands
  const pluginsCommands = _commander2.default.commands.filter(cmd => !cmd._noHelp && cmd._plugin).map(cmd => printCmd(cmd));

  function printList(commands, title) {
    const width = commands.reduce((max, command) => Math.max(max, (0, _stripAnsi2.default)(command[0]).length), 0);
    const comnds = commands.map(cmd => {
      const desc = cmd[1] ? `    ${cmd[1]}` : '';
      return pad(cmd[0], width) + desc;
    }).join('\n').replace(/^/gm, '    ');

    return ['', `  ${_chalk2.default.grey(title)}:`, '', comnds, ''].join('\n');
  }

  let allCommands = [];

  Object.keys(commandGroups).forEach(groupName => {
    allCommands = allCommands.concat(printList(commandGroups[groupName], groupName));
  });

  const pluginsCommandsList = pluginsCommands.length ? printList(pluginsCommands, 'Plugins') : [];

  return allCommands.join('').concat(pluginsCommandsList);
};

_commander2.default.Command.prototype.helpInformation = function () {
  let currentInstance = '';
  if (_session2.default.project && _session2.default.project.instance) {
    const instanceName = _session2.default.project.instance;
    currentInstance = instanceName ? `\n\n  Current Instance: ${_chalk2.default.yellow(instanceName)}` : '';
  }

  const desc = this._description ? [`  ${this._description}`, ''] : [];
  const cmdName = this._alias ? `${this._name}|${this._alias}` : this._name;
  const usage = [`\n  Usage: ${cmdName} ${this.usage()} ${currentInstance}`];

  const commandHelp = this.commandHelp();

  const cmds = commandHelp ? [commandHelp] : [];
  const options = ['  Options:\n', `${this.optionHelp().replace(/^/gm, '    ')}\n\n`];

  return usage.concat(cmds).concat(desc).concat(options).join('\n');
};

exports.default = _commander2.default;
module.exports = exports['default'];
//# sourceMappingURL=program.js.map