"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.importPendingMsg = exports.statusWorkspaceIsCleanMsg = exports.statusInvalidComponentsMsg = exports.statusFailureMsg = void 0;

function _defineProperty2() {
  const data = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

  _defineProperty2 = function () {
    return data;
  };

  return data;
}

function _ramda() {
  const data = _interopRequireDefault(require("ramda"));

  _ramda = function () {
    return data;
  };

  return data;
}

function _chalk() {
  const data = _interopRequireDefault(require("chalk"));

  _chalk = function () {
    return data;
  };

  return data;
}

function _command() {
  const data = _interopRequireDefault(require("../../command"));

  _command = function () {
    return data;
  };

  return data;
}

function _consumer() {
  const data = require("../../../api/consumer");

  _consumer = function () {
    return data;
  };

  return data;
}

function _component() {
  const data = _interopRequireDefault(require("../../../consumer/component"));

  _component = function () {
    return data;
  };

  return data;
}

function _utils() {
  const data = require("../../../utils");

  _utils = function () {
    return data;
  };

  return data;
}

function _chalkBox() {
  const data = require("../../chalk-box");

  _chalkBox = function () {
    return data;
  };

  return data;
}

function _componentIssuesTemplate() {
  const data = require("../../templates/component-issues-template");

  _componentIssuesTemplate = function () {
    return data;
  };

  return data;
}

function _analytics() {
  const data = require("../../../analytics/analytics");

  _analytics = function () {
    return data;
  };

  return data;
}

function _constants() {
  const data = require("../../../constants");

  _constants = function () {
    return data;
  };

  return data;
}

const TROUBLESHOOTING_MESSAGE = `${_chalk().default.yellow(`see troubleshooting at https://${_constants().BASE_DOCS_DOMAIN}/docs/troubleshooting-isolating.html`)}`;
const statusFailureMsg = 'issues found';
exports.statusFailureMsg = statusFailureMsg;
const statusInvalidComponentsMsg = 'invalid components';
exports.statusInvalidComponentsMsg = statusInvalidComponentsMsg;
const statusWorkspaceIsCleanMsg = 'nothing to tag or export (use "bit add <file...>" to track files or directories as components)';
exports.statusWorkspaceIsCleanMsg = statusWorkspaceIsCleanMsg;
const importPendingMsg = 'your workspace has outdated objects. please use "bit import" to pull the latest objects from the remote scope';
exports.importPendingMsg = importPendingMsg;

class Status extends _command().default {
  constructor(...args) {
    super(...args);
    (0, _defineProperty2().default)(this, "name", 'status');
    (0, _defineProperty2().default)(this, "description", `show the working area component(s) status.\n  https://${_constants().BASE_DOCS_DOMAIN}/docs/cli-status.html`);
    (0, _defineProperty2().default)(this, "alias", 's');
    (0, _defineProperty2().default)(this, "opts", [['j', 'json', 'return a json version of the component']]);
    (0, _defineProperty2().default)(this, "loader", true);
    (0, _defineProperty2().default)(this, "migration", true);
    (0, _defineProperty2().default)(this, "json", false);
  }

  action([], {
    json
  }) {
    this.json = json;
    return (0, _consumer().status)();
  }

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


    let showTroubleshootingLink = false;

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

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

    function format(component, showVersions = false, message) {
      const missing = componentsWithMissingDeps.find(missingComp => {
        const compId = component.id ? component.id.toString() : component;
        return missingComp.id.toString() === compId;
      });
      const messageStatus = message ? _chalk().default.yellow(message) : _chalk().default.green('ok');
      if ((0, _utils().isString)(component)) return `${(0, _chalkBox().formatBitString)(component)} ... ${messageStatus}`;
      let bitFormatted = `${(0, _chalkBox().formatNewBit)(component)}`;

      if (showVersions) {
        const localVersions = component.getLocalVersions();
        bitFormatted += `. versions: ${localVersions.join(', ')}`;
      }

      bitFormatted += ' ... ';
      if (!missing) return `${bitFormatted}${messageStatus}`;
      showTroubleshootingLink = true;
      return `${bitFormatted} ${_chalk().default.red(statusFailureMsg)}${formatMissing(missing)}`;
    }

    const importPendingWarning = importPendingComponents.length ? _chalk().default.yellow(`${importPendingMsg}.\n`) : '';

    const splitByMissing = _ramda().default.groupBy(component => {
      return component.includes(statusFailureMsg) ? 'missing' : 'nonMissing';
    });

    const {
      missing,
      nonMissing
    } = splitByMissing(newComponents.map(c => format(c)));

    const outdatedTitle = _chalk().default.underline.white('pending updates');

    const 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';
    const outdatedComps = outdatedComponents.map(component => {
      return `    > ${_chalk().default.cyan(component.id.toStringWithoutVersion())} current: ${component.id.version} latest: ${component.latestVersion}\n`;
    }).join('');
    const outdatedStr = outdatedComponents.length ? [outdatedTitle, outdatedDesc, outdatedComps].join('\n') : '';
    const newComponentDescription = '\n(use "bit tag --all [version]" to lock a version with all your changes)\n';
    const newComponentsTitle = newComponents.length ? _chalk().default.underline.white('new components') + newComponentDescription : '';
    const newComponentsOutput = [newComponentsTitle, ...(nonMissing || []), ...(missing || [])].join('\n');
    const modifiedDesc = '(use "bit diff" to compare changes)\n';
    const modifiedComponentOutput = (0, _utils().immutableUnshift)(modifiedComponent.map(c => format(c)), modifiedComponent.length ? _chalk().default.underline.white('modified components') + newComponentDescription + modifiedDesc : '').join('\n');
    const autoTagPendingOutput = (0, _utils().immutableUnshift)(autoTagPendingComponents.map(c => format(c)), autoTagPendingComponents.length ? _chalk().default.underline.white('components pending to be tagged automatically (when their dependencies are tagged)') : '').join('\n');
    const invalidDesc = '\nthese components were failed to load.\n';
    const invalidComponentOutput = (0, _utils().immutableUnshift)(invalidComponents.map(c => format(c.id.toString(), true, (0, _componentIssuesTemplate().getInvalidComponentLabel)(c.error))).sort(), invalidComponents.length ? _chalk().default.underline.white(statusInvalidComponentsMsg) + invalidDesc : '').join('\n');
    const stagedDesc = '\n(use "bit export <remote_scope> to push these components to a remote scope")\n';
    const stagedComponentsOutput = (0, _utils().immutableUnshift)(stagedComponents.map(c => format(c, true)), stagedComponents.length ? _chalk().default.underline.white('staged components') + stagedDesc : '').join('\n');
    const troubleshootingStr = showTroubleshootingLink ? `\n${TROUBLESHOOTING_MESSAGE}` : '';
    return importPendingWarning + [outdatedStr, newComponentsOutput, modifiedComponentOutput, stagedComponentsOutput, autoTagPendingOutput, invalidComponentOutput].filter(x => x).join(_chalk().default.underline('\n                         \n') + _chalk().default.white('\n')) + troubleshootingStr || _chalk().default.yellow(statusWorkspaceIsCleanMsg);
  }

}

exports.default = Status;