'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'));
}

var _bitId;

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

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

function getLatestVersionNumber(bitIds, bitId) {
  var getParsed = function getParsed(id) {
    return typeof id === 'string' ? (_bitId || _load_bitId()).BitId.parse(id) : id;
  };
  var getString = function getString(id) {
    var ignoreScope = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    var ignoreVersion = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;

    if (!id) return undefined;
    return typeof id === 'string' ? (_bitId || _load_bitId()).BitId.parse(id).toString(ignoreScope, ignoreVersion) : id.toString(ignoreScope, ignoreVersion);
  };

  // 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 commit 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 ignoreScopeAlways = !getParsed(bitId).scope;

  var componentId = getParsed(bitId);
  if (!componentId.getVersion().latest) return bitId;

  var allVersionsForId = [];
  bitIds.map(function (id) {
    if (getString(bitId, ignoreScopeAlways) === getString(id, ignoreScopeAlways)) {
      var version = getParsed(id).getVersion().versionNum;
      if (version) allVersionsForId.push(version);
    }
    return allVersionsForId;
  });

  // A case when the bitId provided 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 = getParsed(bitId).clone();
  bitIdWithMaxVersion.version = maxVersion;
  var result = bitIds.find(function (id) {
    return getString(id, ignoreScopeAlways, false) === getString(bitIdWithMaxVersion, ignoreScopeAlways, false);
  });

  return result;
}
/**
 * Retrive bitId with the highest version from a list according to provided id
 * @description will return the provided id if it's not with latest, if the list contains id without version / with the latest version it will return it
 * @param {BitId[] | string[]} bitIds
 * @param { string | BitId } bitId
 * @returns {string}
 */