'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.statusWorkspaceIsCleanMsg = exports.statusInvalidComponentsMsg = exports.statusFailureMsg = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _ramda;

function _load_ramda() {
  return _ramda = _interopRequireDefault(require('ramda'));
}

var _chalk;

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

var _command;

function _load_command() {
  return _command = _interopRequireDefault(require('../../command'));
}

var _consumer;

function _load_consumer() {
  return _consumer = require('../../../api/consumer');
}

var _component;

function _load_component() {
  return _component = _interopRequireDefault(require('../../../consumer/component'));
}

var _utils;

function _load_utils() {
  return _utils = require('../../../utils');
}

var _chalkBox;

function _load_chalkBox() {
  return _chalkBox = require('../../chalk-box');
}

var _componentIssuesTemplate;

function _load_componentIssuesTemplate() {
  return _componentIssuesTemplate = require('../../templates/component-issues-template');
}

var _analytics;

function _load_analytics() {
  return _analytics = require('../../../analytics/analytics');
}

var _constants;

function _load_constants() {
  return _constants = require('../../../constants');
}

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); } }

function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var TROUBLESHOOTING_MESSAGE = `${(_chalk || _load_chalk()).default.yellow(`see troubleshooting at https://${(_constants || _load_constants()).BASE_DOCS_DOMAIN}/docs/troubleshooting-isolating.html`)}`;

var statusFailureMsg = exports.statusFailureMsg = 'issues found';
var statusInvalidComponentsMsg = exports.statusInvalidComponentsMsg = 'invalid components';
var statusWorkspaceIsCleanMsg = exports.statusWorkspaceIsCleanMsg = 'nothing to tag or export (use "bit add <file...>" to track files or directories as components)';

var Status = function (_Command) {
  _inherits(Status, _Command);

  function Status() {
    var _ref;

    var _temp, _this, _ret;

    _classCallCheck(this, Status);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Status.__proto__ || Object.getPrototypeOf(Status)).call.apply(_ref, [this].concat(args))), _this), _this.name = 'status', _this.description = `show the working area component(s) status.\n  https://${(_constants || _load_constants()).BASE_DOCS_DOMAIN}/docs/cli-status.html`, _this.alias = 's', _this.opts = [['j', 'json', 'return a json version of the component']], _this.loader = true, _this.migration = true, _this.json = false, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(Status, [{
    key: 'action',
    value: function action(_ref2, _ref3) {
      var _ref4 = _toArray(_ref2);

      var json = _ref3.json;

      this.json = json;
      return (0, (_consumer || _load_consumer()).status)();
    }
  }, {
    key: 'report',
    value: function report(_ref5) {
      var newComponents = _ref5.newComponents,
          modifiedComponent = _ref5.modifiedComponent,
          stagedComponents = _ref5.stagedComponents,
          componentsWithMissingDeps = _ref5.componentsWithMissingDeps,
          importPendingComponents = _ref5.importPendingComponents,
          autoTagPendingComponents = _ref5.autoTagPendingComponents,
          invalidComponents = _ref5.invalidComponents,
          outdatedComponents = _ref5.outdatedComponents;

      if (this.json) {
        return JSON.stringify({
          newComponents,
          modifiedComponent: modifiedComponent.map(function (c) {
            return c.id.toString();
          }),
          stagedComponents: stagedComponents.map(function (c) {
            return c.id();
          }),
          componentsWithMissingDeps: componentsWithMissingDeps.map(function (c) {
            return c.id.toString();
          }),
          importPendingComponents: importPendingComponents.map(function (c) {
            return c.id.toString();
          }),
          autoTagPendingComponents,
          invalidComponents,
          outdatedComponents: outdatedComponents.map(function (c) {
            return c.id.toString();
          })
        }, null, 2);
      }
      // If there is problem with at least one component we want to show a link to the
      // troubleshooting doc
      var showTroubleshootingLink = false;

      function formatMissing(missingComponent) {
        function formatMissingStr(key, value, label) {
          if (!value || (_ramda || _load_ramda()).default.isEmpty(value)) return '';
          return (_chalk || _load_chalk()).default.yellow(`\n       ${label}: \n`) + (_chalk || _load_chalk()).default.white(Object.keys(value).map(function (key) {
            return `          ${key} -> ${(0, (_componentIssuesTemplate || _load_componentIssuesTemplate()).componentIssueToString)(value[key])}`;
          }).join('\n'));
        }

        var missingStr = Object.keys((_componentIssuesTemplate || _load_componentIssuesTemplate()).componentIssuesLabels).map(function (key) {
          if (missingComponent.issues[key]) (_analytics || _load_analytics()).Analytics.incExtraDataKey(key);
          return formatMissingStr(key, missingComponent.issues[key], (_componentIssuesTemplate || _load_componentIssuesTemplate()).componentIssuesLabels[key]);
        }).join('');
        return `       ${missingStr}\n`;
      }

      function format(component) {
        var showVersions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
        var message = arguments[2];

        var missing = componentsWithMissingDeps.find(function (missingComp) {
          var compId = component.id ? component.id.toString() : component;
          return missingComp.id.toString() === compId;
        });
        var messageStatus = message ? (_chalk || _load_chalk()).default.yellow(message) : (_chalk || _load_chalk()).default.green('ok');

        if ((0, (_utils || _load_utils()).isString)(component)) return `${(0, (_chalkBox || _load_chalkBox()).formatBitString)(component)} ... ${messageStatus}`;
        var bitFormatted = `${(0, (_chalkBox || _load_chalkBox()).formatNewBit)(component)}`;
        if (showVersions) {
          var localVersions = component.getLocalVersions();
          bitFormatted += `. versions: ${localVersions.join(', ')}`;
        }
        bitFormatted += ' ... ';
        if (!missing) return `${bitFormatted}${messageStatus}`;
        showTroubleshootingLink = true;
        return `${bitFormatted} ${(_chalk || _load_chalk()).default.red(statusFailureMsg)}${formatMissing(missing)}`;
      }

      var importPendingWarning = importPendingComponents.length ? (_chalk || _load_chalk()).default.yellow('your workspace has outdated objects. please use "bit import" to pull the latest objects from the remote scope.\n') : '';

      var splitByMissing = (_ramda || _load_ramda()).default.groupBy(function (component) {
        return component.includes(statusFailureMsg) ? 'missing' : 'nonMissing';
      });

      var _splitByMissing = splitByMissing(newComponents.map(function (c) {
        return format(c);
      })),
          missing = _splitByMissing.missing,
          nonMissing = _splitByMissing.nonMissing;

      var outdatedTitle = (_chalk || _load_chalk()).default.underline.white('pending updates');
      var outdatedDesc = '(use "bit checkout [version] [component_id]" to merge changes)\n(use "bit diff [component_id] [new_version]" to compare changes)\n(use "bit log [component_id]" to list all available versions)\n';
      var outdatedComps = outdatedComponents.map(function (component) {
        return `    > ${(_chalk || _load_chalk()).default.cyan(component.id.toStringWithoutVersion())} current: ${component.id.version} latest: ${component.latestVersion}\n`;
      }).join('');

      var outdatedStr = outdatedComponents.length ? [outdatedTitle, outdatedDesc, outdatedComps].join('\n') : '';

      var newComponentDescription = '\n(use "bit tag --all [version]" to lock a version with all your changes)\n';
      var newComponentsTitle = newComponents.length ? (_chalk || _load_chalk()).default.underline.white('new components') + newComponentDescription : '';

      var newComponentsOutput = [newComponentsTitle].concat(_toConsumableArray(nonMissing || []), _toConsumableArray(missing || [])).join('\n');

      var modifiedDesc = '(use "bit diff" to compare changes)\n';
      var modifiedComponentOutput = (0, (_utils || _load_utils()).immutableUnshift)(modifiedComponent.map(function (c) {
        return format(c);
      }), modifiedComponent.length ? (_chalk || _load_chalk()).default.underline.white('modified components') + newComponentDescription + modifiedDesc : '').join('\n');

      var autoTagPendingOutput = (0, (_utils || _load_utils()).immutableUnshift)(autoTagPendingComponents.map(function (c) {
        return format(c);
      }), autoTagPendingComponents.length ? (_chalk || _load_chalk()).default.underline.white('components pending to be tagged automatically (when their dependencies are tagged)') : '').join('\n');

      var invalidDesc = '\nthese components were failed to load.\n';
      var invalidComponentOutput = (0, (_utils || _load_utils()).immutableUnshift)(invalidComponents.map(function (c) {
        return format(c.id.toString(), true, (0, (_componentIssuesTemplate || _load_componentIssuesTemplate()).getInvalidComponentLabel)(c.error));
      }).sort(), invalidComponents.length ? (_chalk || _load_chalk()).default.underline.white(statusInvalidComponentsMsg) + invalidDesc : '').join('\n');

      var stagedDesc = '\n(use "bit export <remote_scope> to push these components to a remote scope")\n';
      var stagedComponentsOutput = (0, (_utils || _load_utils()).immutableUnshift)(stagedComponents.map(function (c) {
        return format(c, true);
      }), stagedComponents.length ? (_chalk || _load_chalk()).default.underline.white('staged components') + stagedDesc : '').join('\n');

      var troubleshootingStr = showTroubleshootingLink ? `\n${TROUBLESHOOTING_MESSAGE}` : '';

      return importPendingWarning + [outdatedStr, newComponentsOutput, modifiedComponentOutput, stagedComponentsOutput, autoTagPendingOutput, invalidComponentOutput].filter(function (x) {
        return x;
      }).join((_chalk || _load_chalk()).default.underline('\n                         \n') + (_chalk || _load_chalk()).default.white('\n')) + troubleshootingStr || (_chalk || _load_chalk()).default.yellow(statusWorkspaceIsCleanMsg);
    }
  }]);

  return Status;
}((_command || _load_command()).default);

exports.default = Status;