'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.removeLocalVersionsForAllComponents = exports.removeLocalVersion = undefined;

var _regenerator;

function _load_regenerator() {
  return _regenerator = _interopRequireDefault(require('babel-runtime/regenerator'));
}

/**
 * If not specified version, remove all local versions.
 */
var removeLocalVersion = exports.removeLocalVersion = function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee(scope, id, version) {
    var force = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
    var component, localVersions, idStr, versionsToRemove, dependencyGraph;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return scope.getComponentModel(id);

          case 2:
            component = _context.sent;
            localVersions = component.getLocalVersions();
            idStr = id.toString();

            if (localVersions.length) {
              _context.next = 7;
              break;
            }

            throw new (_generalError || _load_generalError()).default(`unable to untag ${idStr}, the component is not staged`);

          case 7:
            if (!(version && !component.hasVersion(version))) {
              _context.next = 9;
              break;
            }

            throw new (_generalError || _load_generalError()).default(`unable to untag ${idStr}, the version ${version} does not exist`);

          case 9:
            if (!(version && !localVersions.includes(version))) {
              _context.next = 11;
              break;
            }

            throw new (_generalError || _load_generalError()).default(`unable to untag ${idStr}, the version ${version} was exported already`);

          case 11:
            versionsToRemove = version ? [version] : localVersions;

            if (force) {
              _context.next = 17;
              break;
            }

            _context.next = 15;
            return scope.getDependencyGraph();

          case 15:
            dependencyGraph = _context.sent;


            versionsToRemove.forEach(function (versionToRemove) {
              var idWithVersion = component.toBitId().changeVersion(versionToRemove);
              var dependents = dependencyGraph.getDependentsPerId(idWithVersion);
              if (dependents.length) {
                throw new (_generalError || _load_generalError()).default(`unable to untag ${idStr}, the version ${versionToRemove} has the following dependent(s) ${dependents.join(', ')}`);
              }
            });

          case 17:
            _context.next = 19;
            return Promise.all(versionsToRemove.map(function (ver) {
              return scope.sources.removeVersion(component, ver, false);
            }));

          case 19:
            _context.next = 21;
            return scope.objects.persist();

          case 21:
            if (component.versionArray.length) {
              _context.next = 24;
              break;
            }

            _context.next = 24;
            return component.remove(scope.objects);

          case 24:
            return _context.abrupt('return', { id, versions: versionsToRemove, component });

          case 25:
          case 'end':
            return _context.stop();
        }
      }
    }, _callee, this);
  }));

  return function removeLocalVersion(_x2, _x3, _x4) {
    return _ref.apply(this, arguments);
  };
}();

var removeLocalVersionsForAllComponents = exports.removeLocalVersionsForAllComponents = function () {
  var _ref2 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee2(scope, version) {
    var force = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
    var components, candidateComponents, versionOutput, dependencyGraph, candidateComponentsIds, candidateComponentsIdsStr;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            _context2.next = 2;
            return scope.objects.listComponents(false);

          case 2:
            components = _context2.sent;
            candidateComponents = components.filter(function (component) {
              var localVersions = component.getLocalVersions();
              if (!localVersions.length) return false;
              return version ? localVersions.includes(version) : true;
            });

            if (candidateComponents.length) {
              _context2.next = 7;
              break;
            }

            versionOutput = version ? `${version} ` : '';
            throw new (_generalError || _load_generalError()).default(`no components found with version ${versionOutput}to untag on your workspace`);

          case 7:
            if (!(!force && version)) {
              _context2.next = 14;
              break;
            }

            _context2.next = 10;
            return scope.getDependencyGraph();

          case 10:
            dependencyGraph = _context2.sent;
            candidateComponentsIds = candidateComponents.map(function (component) {
              var bitId = component.toBitId();
              return bitId.changeVersion(version);
            });
            candidateComponentsIdsStr = candidateComponentsIds.map(function (id) {
              return id.toString();
            });


            candidateComponentsIds.forEach(function (bitId) {
              var dependents = dependencyGraph.getDependentsPerId(bitId);
              var dependentsNotCandidates = dependents.filter(function (dependent) {
                return !candidateComponentsIdsStr.includes(dependent);
              });
              if (dependentsNotCandidates.length) {
                throw new (_generalError || _load_generalError()).default( // $FlowFixMe
                `unable to untag ${bitId}, the version ${version} has the following dependent(s) ${dependents.join(', ')}`);
              }
            });

          case 14:

            (_logger || _load_logger()).default.debug(`found ${candidateComponents.length} components to untag`);
            return _context2.abrupt('return', Promise.all(candidateComponents.map(function (component) {
              return removeLocalVersion(scope, component.toBitId(), version, true);
            })));

          case 16:
          case 'end':
            return _context2.stop();
        }
      }
    }, _callee2, this);
  }));

  return function removeLocalVersionsForAllComponents(_x6, _x7) {
    return _ref2.apply(this, arguments);
  };
}();

var _bitId;

function _load_bitId() {
  return _bitId = require('../../bit-id');
}

var _component;

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

var _logger;

function _load_logger() {
  return _logger = _interopRequireDefault(require('../../logger/logger'));
}

var _;

function _load_() {
  return _ = require('..');
}

var _generalError;

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

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

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }