"use strict";

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

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

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

  _ramda = function () {
    return data;
  };

  return data;
}

function _semver() {
  const data = _interopRequireDefault(require("semver"));

  _semver = function () {
    return data;
  };

  return data;
}

/**
 * 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

  const ignoreScope = !bitId.hasScope();
  const similarIds = ignoreScope ? bitIds.filterWithoutScopeAndVersion(bitId) : bitIds.filterWithoutVersion(bitId);
  const allVersionsForId = similarIds.filter(id => id.hasVersion()).map(id => id.version); // A case when the provided bitId doesn't exists in the array

  if (_ramda().default.isEmpty(allVersionsForId)) return bitId;

  const maxVersion = _semver().default.maxSatisfying(allVersionsForId, '*');

  const bitIdWithMaxVersion = bitId.changeVersion(maxVersion);
  const 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;
}