'use strict';

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

var _chalk;

function _load_chalk() {
  return _chalk = _interopRequireDefault(require('chalk'));
}

var _table;

function _load_table() {
  return _table = require('table');
}

var _padRight;

function _load_padRight() {
  return _padRight = _interopRequireDefault(require('pad-right'));
}

var _consumerComponent;

function _load_consumerComponent() {
  return _consumerComponent = _interopRequireDefault(require('../../consumer/component/consumer-component'));
}

var _docsTemplate;

function _load_docsTemplate() {
  return _docsTemplate = _interopRequireDefault(require('./docs-template'));
}

var _componentsObjectDiff;

function _load_componentsObjectDiff() {
  return _componentsObjectDiff = require('../../consumer/component-ops/components-object-diff');
}

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

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

var COLUMN_WIDTH = 50;
var tableColumnConfig = {
  columns: {
    // $FlowFixMe
    1: {
      alignment: 'left',
      width: COLUMN_WIDTH
    },
    // $FlowFixMe
    2: {
      alignment: 'left',
      width: COLUMN_WIDTH
    }
  }
};

var fields = ['id', 'compiler', 'tester', 'language', 'mainFile', 'dependencies', 'devDependencies', 'compilerDependencies', 'testerDependencies', 'packages', 'devPackages', 'peerDependencies', 'files', 'specs', 'deprecated'];

function generateDependenciesTable(component, showRemoteVersion) {
  if (!component.hasDependencies()) {
    return '';
  }

  var dependencyHeader = [];
  if (showRemoteVersion) {
    dependencyHeader.push(['Dependency ID', 'Current Version', 'Local Version', 'Remote Version']);
  } else {
    dependencyHeader.push(['Dependencies']);
  }
  var getDependenciesRows = function getDependenciesRows(dependencies, title) {
    var dependencyRows = [];
    dependencies.forEach(function (dependency) {
      var dependencyId = showRemoteVersion ? dependency.id.toStringWithoutVersion() : dependency.id.toString();
      dependencyId = title ? `${dependencyId} (${title})` : dependencyId;
      var row = [dependencyId];
      if (showRemoteVersion) {
        var dependencyVersion = dependency.currentVersion;
        var localVersion = dependency.localVersion;
        var remoteVersion = dependency.remoteVersion ? dependency.remoteVersion : null;
        // if all versions are equal, paint them with green. Otherwise, paint with red
        var color = remoteVersion && remoteVersion === localVersion && remoteVersion === dependencyVersion || !remoteVersion && localVersion === dependencyVersion ? 'green' : 'red';
        // $FlowFixMe
        row.push((_chalk || _load_chalk()).default[color](dependencyVersion));
        // $FlowFixMe
        row.push((_chalk || _load_chalk()).default[color](localVersion));
        // $FlowFixMe
        row.push(remoteVersion ? (_chalk || _load_chalk()).default[color](remoteVersion) : 'N/A');
      }
      dependencyRows.push(row);
    });
    return dependencyRows;
  };
  var dependenciesRows = getDependenciesRows(component.dependencies.get());
  var devDependenciesRows = getDependenciesRows(component.devDependencies.get(), 'dev');
  var compilerDependenciesRows = getDependenciesRows(component.compilerDependencies.get(), 'compiler');
  var testerDependenciesRows = getDependenciesRows(component.testerDependencies.get(), 'tester');
  var allDependenciesRows = [].concat(_toConsumableArray(dependenciesRows), _toConsumableArray(devDependenciesRows), _toConsumableArray(compilerDependenciesRows), _toConsumableArray(testerDependenciesRows));

  var dependenciesTable = (0, (_table || _load_table()).table)(dependencyHeader.concat(allDependenciesRows));
  return dependenciesTable;
}

function calculatePadRightLength(str, columnWidth) {
  if (!str) return '';
  var padRightCount = Math.ceil(str.length / columnWidth) * columnWidth;
  return str.length > columnWidth ? (0, (_padRight || _load_padRight()).default)(str, padRightCount, ' ') : (0, (_padRight || _load_padRight()).default)(str, columnWidth, ' ');
}

function paintWithoutCompare(component, showRemoteVersion) {
  var printableComponent = (0, (_componentsObjectDiff || _load_componentsObjectDiff()).componentToPrintableForDiff)(component);
  var rows = fields.map(function (field) {
    var arr = [];

    var title = (0, (_componentsObjectDiff || _load_componentsObjectDiff()).prettifyFieldName)(field);
    if (!printableComponent[field]) return null;

    arr.push((_chalk || _load_chalk()).default.cyan(title));
    if (!printableComponent[field]) return null;

    if (printableComponent[field]) {
      if (printableComponent[field] instanceof Array) {
        arr.push(printableComponent[field].map(function (str) {
          return calculatePadRightLength(str, COLUMN_WIDTH);
        }).join(' ').trim());
      } else arr.push(printableComponent[field]);
    }
    return arr;
  }).filter(function (x) {
    return x;
  });

  var componentTable = (0, (_table || _load_table()).table)(rows, tableColumnConfig);
  var dependenciesTableStr = showRemoteVersion ? generateDependenciesTable(component, showRemoteVersion) : '';
  return componentTable + dependenciesTableStr + (0, (_docsTemplate || _load_docsTemplate()).default)(component.docs);
}

function paintWithCompare(originalComponent, componentToCompareTo, showRemoteVersion) {
  var printableOriginalComponent = (0, (_componentsObjectDiff || _load_componentsObjectDiff()).componentToPrintableForDiff)(originalComponent);
  printableOriginalComponent.id += ' [file system]';
  var printableComponentToCompare = (0, (_componentsObjectDiff || _load_componentsObjectDiff()).componentToPrintableForDiff)(componentToCompareTo);

  var componentsDiffs = (0, (_componentsObjectDiff || _load_componentsObjectDiff()).getDiffBetweenObjects)(printableOriginalComponent, printableComponentToCompare);

  var rows = fields.map(function (field) {
    var arr = [];
    if (!printableOriginalComponent[field] && !printableComponentToCompare[field]) return null;
    var title = `${field[0].toUpperCase()}${field.substr(1)}`.replace(/([A-Z])/g, ' $1').trim();
    arr.push(field in componentsDiffs && field !== 'id' ? (_chalk || _load_chalk()).default.red(title) : (_chalk || _load_chalk()).default.cyan(title));
    if (printableComponentToCompare[field] instanceof Array) {
      arr.push(printableComponentToCompare[field].map(function (str) {
        return calculatePadRightLength(str, COLUMN_WIDTH);
      }).join(' ').trim());
    } else {
      arr.push(printableComponentToCompare[field]);
    }
    if (printableOriginalComponent[field] instanceof Array) {
      arr.push(printableOriginalComponent[field].map(function (str) {
        return calculatePadRightLength(str, COLUMN_WIDTH);
      }).join(' ').trim());
    } else {
      arr.push(printableOriginalComponent[field]);
    }
    return arr;
  }).filter(function (x) {
    return x;
  });

  var componentTable = (0, (_table || _load_table()).table)(rows, tableColumnConfig);
  var dependenciesTableStr = !componentToCompareTo ? generateDependenciesTable(originalComponent, showRemoteVersion) : '';
  return componentTable + dependenciesTableStr;
}

exports.default = function (component, componentModel, showRemoteVersion) {
  return componentModel ? paintWithCompare(component, componentModel, showRemoteVersion) : paintWithoutCompare(component, showRemoteVersion);
};