'use strict';

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

var _semver;

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

var _logger;

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

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

/**
 * A function which get a migration manifest and versions, and return a sorted array of the migrations to run
 * We are taking also the current version to prevent cases which a developer specify a migration to run for a
 * future release, and we don't want it to run now
 *
 * @export
 * @param {string} currentVersion - The current version of bit
 * @param {string} storeVersion  - The version of the store to check (for example scope version or .bit.map.json version)
 * @param {Object} migratonManifest  - A manifest which contain all the existing migrations
 * @param {boolean} [verbose=false] - Print logs
 * @returns {Object[]} - Sorted array of migrations to run
 */
function getMigrationVersions(currentVersion, storeVersion, migratonManifest) {
  var verbose = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;

  if (currentVersion === storeVersion) return [];
  // Get all the versions which contain at least one migration
  var migrationsVersions = Object.keys(migratonManifest);
  // Get migration versions which is between the current version and the store version
  var migrationsVersionsToRun = migrationsVersions.filter(function (version) {
    return (_semver || _load_semver()).default.satisfies(version, `>${storeVersion} <=${currentVersion}`);
  });
  // Sort the migration to run them from the oldest version to the newest (in case i update my client and there is few versions in between with
  // migration process)
  var sortedMigrationVersionsToRun = migrationsVersionsToRun.sort((_semver || _load_semver()).default.compare);
  // Get the result with the actual functions
  var sortedMigrationToRun = sortedMigrationVersionsToRun.map(function (migrationVersion) {
    return {
      [migrationVersion]: migratonManifest[migrationVersion]
    };
  });
  var infoMessage = sortedMigrationVersionsToRun.length ? `Found the following versions that need migration ${sortedMigrationVersionsToRun.join(', ')}` : 'none of the versions has migration to run';
  (_logger || _load_logger()).default.debug(infoMessage);
  if (verbose) {
    console.log(infoMessage); // eslint-disable-line no-console
  }
  return sortedMigrationToRun;
}