'use strict';

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

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

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 _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 _component2;

function _load_component2() {
  return _component2 = _interopRequireDefault(require('../../../scope/models/component'));
}

var _constants;

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

var _generalError;

function _load_generalError() {
  return _generalError = _interopRequireDefault(require('../../../error/general-error'));
}

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

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 chalk = require('chalk');

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

  function Export() {
    var _ref;

    var _temp, _this, _ret;

    _classCallCheck(this, Export);

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

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Export.__proto__ || Object.getPrototypeOf(Export)).call.apply(_ref, [this].concat(args))), _this), _this.name = 'tag [id] [version]', _this.description = `record component changes and lock versions.\n  https://${(_constants || _load_constants()).BASE_DOCS_DOMAIN}/docs/versioning-tracked-components.html`, _this.alias = 't', _this.opts = [['m', 'message <message>', 'log message describing the user changes'], ['a', 'all [version]', 'tag all new and modified components'], ['s', 'scope <version>', 'tag all components of the current scope'], ['p', 'patch', 'increment the patch version number'], ['mi', 'minor', 'increment the minor version number'], ['ma', 'major', 'increment the major version number'], ['f', 'force', 'forcely tag even if tests are failing and even when component has not changed'], ['v', 'verbose', 'show specs output on failure'], ['i', 'ignore-missing-dependencies', 'ignore missing dependencies (default = false)'], ['I', 'ignore-newest-version', 'ignore existing of newer versions (default = false)']], _this.loader = true, _this.migration = true, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(Export, [{
    key: 'action',
    value: function action(_ref2, _ref3) {
      var _ref4 = _slicedToArray(_ref2, 2),
          id = _ref4[0],
          version = _ref4[1];

      var message = _ref3.message,
          all = _ref3.all,
          patch = _ref3.patch,
          minor = _ref3.minor,
          major = _ref3.major,
          force = _ref3.force,
          verbose = _ref3.verbose,
          _ref3$ignoreMissingDe = _ref3.ignoreMissingDependencies,
          ignoreMissingDependencies = _ref3$ignoreMissingDe === undefined ? false : _ref3$ignoreMissingDe,
          _ref3$ignoreNewestVer = _ref3.ignoreNewestVersion,
          ignoreNewestVersion = _ref3$ignoreNewestVer === undefined ? false : _ref3$ignoreNewestVer,
          scope = _ref3.scope;

      function getVersion() {
        if (scope) return scope;
        if (all && (0, (_utils || _load_utils()).isString)(all)) return all;
        return version;
      }

      if (!id && !all && !scope) {
        throw new (_generalError || _load_generalError()).default('missing [id]. to tag all components, please use --all flag');
      }
      if (id && all) {
        throw new (_generalError || _load_generalError()).default('you can use either a specific component [id] to tag a particular component or --all flag to tag them all');
      }

      var releaseFlags = [patch, minor, major].filter(function (x) {
        return x;
      });
      if (releaseFlags.length > 1) {
        return Promise.reject('you can use only one of the following - patch, minor, major');
      }

      // const releaseType = major ? 'major' : (minor ? 'minor' : (patch ? 'patch' : DEFAULT_BIT_RELEASE_TYPE));
      var releaseType = (_constants || _load_constants()).DEFAULT_BIT_RELEASE_TYPE;
      var includeImported = scope && all;

      if (major) releaseType = 'major';else if (minor) releaseType = 'minor';else if (patch) releaseType = 'patch';

      if (all || scope) {
        return (0, (_consumer || _load_consumer()).commitAllAction)({
          message: message || '',
          exactVersion: getVersion(),
          releaseType,
          force,
          verbose,
          ignoreMissingDependencies,
          ignoreNewestVersion,
          scope,
          includeImported
        });
      }
      return (0, (_consumer || _load_consumer()).commitAction)({
        id,
        message,
        exactVersion: getVersion(),
        releaseType,
        force,
        verbose,
        ignoreMissingDependencies,
        ignoreNewestVersion
      });
    }
  }, {
    key: 'report',
    value: function report(results) {
      if (!results) return chalk.yellow('nothing to tag');
      var taggedComponents = results.taggedComponents,
          autoTaggedComponents = results.autoTaggedComponents,
          warnings = results.warnings,
          newComponents = results.newComponents;

      function joinComponents(comps) {
        return comps.map(function (comp) {
          if (comp instanceof (_component2 || _load_component2()).default) return comp.id();
          return comp.id.toString();
        }).join(', ');
      }

      function outputIfExists(comps, label, breakBefore) {
        if (comps.length !== 0) {
          var str = '';
          if (breakBefore) str = '\n';
          str += `${chalk.cyan(label)} ${joinComponents(comps)}`;
          return str;
        }

        return '';
      }

      // send only non new components to changed components compare
      var changedComponents = taggedComponents.filter(function (component) {
        return !newComponents.includes(component.id.toStringWithoutVersion());
      });
      var addedComponents = taggedComponents.filter(function (component) {
        return newComponents.includes(component.id.toStringWithoutVersion());
      });
      var autoTaggedCount = autoTaggedComponents ? autoTaggedComponents.length : 0;

      var warningsOutput = warnings && warnings.length ? `${chalk.yellow(warnings.join('\n'))}\n\n` : '';

      return warningsOutput + chalk.green(`${taggedComponents.length + autoTaggedCount} components tagged`) + chalk.gray(` | ${addedComponents.length} added, ${changedComponents.length} changed, ${autoTaggedCount} auto-tagged`) + outputIfExists(addedComponents, 'added components: ', true) + outputIfExists(changedComponents, 'changed components: ', true) + outputIfExists(autoTaggedComponents, 'auto-tagged components (as a result of tagging their dependencies): ', true);
    }
  }]);

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

exports.default = Export;