"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.formatData = formatData;
exports.formatEnvironment = formatEnvironment;
exports.keyValue = keyValue;
exports.requoteArgs = requoteArgs;
exports.getGlyphForStatus = getGlyphForStatus;
exports.formatJobSteps = formatJobSteps;
exports.RunningSprite = exports.RUNNING_SPRITE_GLYPHS = void 0;

var _chalk = _interopRequireDefault(require("chalk"));

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

/** @format */

/**
 * External dependencies
 */
function formatData(data, format, opts) {
  if (!data || !data.length) {
    return '';
  }

  switch (format) {
    case 'ids':
      return ids(data, opts);

    case 'json':
      return JSON.stringify(data, null, '\t');

    case 'csv':
      return csv(data, opts);

    case 'keyValue':
      return keyValue(data, opts);

    case 'table':
    default:
      return table(data, opts);
  }
}

function formatEnvironment(environment) {
  if ('production' === environment.toLowerCase()) {
    return _chalk.default.red(environment.toUpperCase());
  }

  return _chalk.default.blueBright(environment.toLowerCase());
}

function ids(data) {
  const fields = Object.keys(data[0]).map(key => key.toLowerCase());

  if (0 > fields.indexOf('id')) {
    return 'No ID field found';
  }

  const id = [];
  data.forEach(d => id.push(d.id));
  return id.join(' ');
}

function csv(data) {
  const json2csv = require('json2csv');

  const fields = Object.keys(data[0]);
  return json2csv({
    data: data,
    fields: formatFields(fields)
  });
}

function table(data) {
  const Table = require('cli-table');

  const fields = Object.keys(data[0]);
  const t = new Table({
    head: formatFields(fields),
    style: {
      head: ['blueBright']
    }
  });
  data.forEach(d => {
    const row = [];
    fields.forEach(h => row.push(d[h]));
    t.push(row);
  });
  return t.toString();
}

function formatFields(fields) {
  return fields.map(field => {
    return field.split(/(?=[A-Z])/).join(' ').toLowerCase();
  });
}

function keyValue(values) {
  const lines = [];
  const pairs = values.length > 0;
  pairs ? lines.push('===================================') : '';

  for (const i of values) {
    let v = i.value;

    switch (i.key.toLowerCase()) {
      case 'environment':
        v = formatEnvironment(v);
        break;
    }

    lines.push(`+ ${i.key}: ${v}`);
  }

  lines.push('===================================');
  return lines.join('\n');
}

function requoteArgs(args) {
  return args.map(arg => {
    if (arg.includes('--') && arg.includes('=') && arg.includes(' ')) {
      return arg.replace(/^--(.*)=(.*)$/, '--$1="$2"');
    }

    if (arg.includes(' ')) {
      return `"${arg}"`;
    }

    return arg;
  });
}

const RUNNING_SPRITE_GLYPHS = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
exports.RUNNING_SPRITE_GLYPHS = RUNNING_SPRITE_GLYPHS;

class RunningSprite {
  constructor() {
    this.i = 0;
  }

  next() {
    if (++this.i >= RUNNING_SPRITE_GLYPHS.length) {
      this.i = 0;
    }
  }

  toString() {
    const glyph = RUNNING_SPRITE_GLYPHS[this.i];
    this.next(); // TODO: throttle

    return glyph;
  }

}

exports.RunningSprite = RunningSprite;

function getGlyphForStatus(status, runningSprite) {
  switch (status) {
    case 'pending':
      return '○';

    case 'running':
      return _chalk.default.blueBright(runningSprite);

    case 'success':
      return _chalk.default.green('✓');

    case 'failed':
      return _chalk.default.red('✕');

    case 'unknown':
      return _chalk.default.yellow('✕');
  }
}

function formatJobSteps(steps, runningSprite) {
  return steps.reduce((carry, step) => carry + `- ${step.name}: ${getGlyphForStatus(step.status, runningSprite)}\n`, '');
}