'use strict';

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

var _regenerator;

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

var _bluebird;

function _load_bluebird() {
  return _bluebird = require('bluebird');
}

/**
 * If not specified version, remove all local versions.
 */
var removeLocalVersion = exports.removeLocalVersion = function () {
  var _ref = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__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.getModelComponentIgnoreScope(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:

            scope.sources.removeComponentVersions(component, versionsToRemove);

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

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

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

var removeLocalVersionsForAllComponents = exports.removeLocalVersionsForAllComponents = function () {
  var _ref2 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee2(scope, version) {
    var force = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
    var componentsToUntag;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            _context2.next = 2;
            return getComponentsWithOptionToUntag(scope, version);

          case 2:
            componentsToUntag = _context2.sent;
            return _context2.abrupt('return', removeLocalVersionsForMultipleComponents(componentsToUntag, version, force, scope));

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

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

var removeLocalVersionsForComponentsMatchedByWildcard = exports.removeLocalVersionsForComponentsMatchedByWildcard = function () {
  var _ref3 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee3(scope, version) {
    var force = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
    var idWithWildcard = arguments[3];
    var candidateComponents, componentsToUntag;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            _context3.next = 2;
            return getComponentsWithOptionToUntag(scope, version);

          case 2:
            candidateComponents = _context3.sent;
            componentsToUntag = idWithWildcard ? (_componentsList || _load_componentsList()).default.filterComponentsByWildcard(candidateComponents, idWithWildcard) : candidateComponents;
            return _context3.abrupt('return', removeLocalVersionsForMultipleComponents(componentsToUntag, version, force, scope));

          case 5:
          case 'end':
            return _context3.stop();
        }
      }
    }, _callee3, this);
  }));

  return function removeLocalVersionsForComponentsMatchedByWildcard(_x8, _x9) {
    return _ref3.apply(this, arguments);
  };
}();

var removeLocalVersionsForMultipleComponents = function () {
  var _ref4 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee4(componentsToUntag, version, force, scope) {
    var versionOutput, dependencyGraph, candidateComponentsIds, candidateComponentsIdsStr;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            if (componentsToUntag.length) {
              _context4.next = 3;
              break;
            }

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

          case 3:
            if (!(!force && version)) {
              _context4.next = 10;
              break;
            }

            _context4.next = 6;
            return scope.getDependencyGraph();

          case 6:
            dependencyGraph = _context4.sent;
            candidateComponentsIds = componentsToUntag.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 10:
            (_logger || _load_logger()).default.debug(`found ${componentsToUntag.length} components to untag`);
            return _context4.abrupt('return', Promise.all(componentsToUntag.map(function (component) {
              return removeLocalVersion(scope, component.toBitId(), version, true);
            })));

          case 12:
          case 'end':
            return _context4.stop();
        }
      }
    }, _callee4, this);
  }));

  return function removeLocalVersionsForMultipleComponents(_x11, _x12, _x13, _x14) {
    return _ref4.apply(this, arguments);
  };
}();

var getComponentsWithOptionToUntag = function () {
  var _ref5 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee5(scope, version) {
    var components, candidateComponents;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee5$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            _context5.next = 2;
            return scope.list();

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

          case 5:
          case 'end':
            return _context5.stop();
        }
      }
    }, _callee5, this);
  }));

  return function getComponentsWithOptionToUntag(_x15, _x16) {
    return _ref5.apply(this, arguments);
  };
}();

var _bitId;

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

var _modelComponent;

function _load_modelComponent() {
  return _modelComponent = _interopRequireDefault(require('../models/model-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'));
}

var _componentsList;

function _load_componentsList() {
  return _componentsList = _interopRequireDefault(require('../../consumer/component/components-list'));
}

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