'use strict';

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

var _ramda;

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

var _semver;

function _load_semver() {
  return _semver = _interopRequireDefault(require('semver'));
}

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

/**
 * Retrieve bitId with the highest version from a list according to provided id
 * it returns the provided id if it has a version already
 * if the list contains id without version, it returns the provided id.
 */
function getLatestVersionNumber(bitIds, bitId) {
  if (!bitId.getVersion().latest) return bitId;

  // If the bitId provided doesn't contain version we want to ignore scope during search always
  // otherwise we will have problems finding the version from the bitmap after we export the component
  // because we tag with a name without scope but the bitmap contain it with the scope name since it was exported
  // without this, we will always just return the first component in the bitmap which is really bad
  var ignoreScope = !bitId.hasScope();

  var similarIds = ignoreScope ? bitIds.filterWithoutScopeAndVersion(bitId) : bitIds.filterWithoutVersion(bitId);
  var allVersionsForId = similarIds.filter(function (id) {
    return id.hasVersion();
  }).map(function (id) {
    return id.version;
  });

  // A case when the provided bitId doesn't exists in the array
  if ((_ramda || _load_ramda()).default.isEmpty(allVersionsForId)) return bitId;

  var maxVersion = (_semver || _load_semver()).default.maxSatisfying(allVersionsForId, '*');
  var bitIdWithMaxVersion = bitId.changeVersion(maxVersion);
  var result = ignoreScope ? bitIds.searchWithoutScope(bitIdWithMaxVersion) : bitIds.search(bitIdWithMaxVersion);
  if (!result) {
    throw new Error(`getLatestVersionNumber failed to find the id ${bitIdWithMaxVersion.toString()} within bitIds`);
  }

  return result;
}