'use strict';

// externals

// local
const tools = require('../../utils/tools');
const metadataUtils = require('../metadata/metadata-utils');

// inner modules
const innerCommon = require('./common');
const innerPackageCommon = require('./package-common');



// for env-based build, we take the latest TST release version as the base
module.exports.getNewVersion = (pkg, envTarget) => {
  let versionsMetadata;
  let envsMetadata;
  let currentVersion;

  return Promise.resolve()
    // get current version
    .then(() => {
      return innerPackageCommon.getCurrentVersion(pkg);
    })
    .then((version) => {
      currentVersion = version;
    })

    // fetch versions history and store
    .then(() => {
      return metadataUtils.remotePackage.getMetadataVersions(pkg);
    })
    .then((metadata) => {
      versionsMetadata = metadata;
    })

    // fetch envs metadata and store
    .then(() => {
      return metadataUtils.remotePackage.getMetadataEnvs(pkg);
    })
    .then((metadata) => {
      envsMetadata = metadata;
    })


    // generating new version based on the env target and the envs cycle type
    .then(() => {
      return innerCommon.getNewVersionDefault(envTarget, versionsMetadata, envsMetadata, currentVersion);
    })

    .catch((e) => {
      throw e;
    })
}
