'use strict';

// externals
const semver = require('semver');
const path = require('path');

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

// inner
const appCommon = require('./app-common');

// fetch args
const { dryRun } = tools.getArgs();


// for process v1 build, version is updated in the project package.json
// new version is derived from there

module.exports.getNewVersion = (project, isSnapshot, isSupportBranch) => {
  return Promise.resolve()
    .then(() => {
      return appCommon.getCurrentVersion(project);
    })
    .then((version) => {
      // if the project has specific version strategy defined
      if (project.build && project.build.versionStrategy) {

          // version depends on the root package version defined
          if (project.build.versionStrategy.type === 'ROOT_PACKAGE') {
            const nmPath = path.join(process.cwd(), 'node_modules', project.build.versionStrategy.rootPackageName);
            const rootPackageVersion = require(path.join(nmPath, 'package.json')).version;
            return rootPackageVersion;
          }

      // normal flow is applied : develop branch => minor / master branch => major / supportBranch => patch
      } else {
        if (isSnapshot) {
          return semver.inc(version, 'minor');
        } else {
          if (isSupportBranch) {
            return semver.inc(version, 'patch');
          } else {
            return semver.inc(version, 'major');
          }
        }
      }
    })
    .catch((e) => {
      throw e;
    })
}



module.exports.updatePackageVersion = (project, newVersion) => {
  return Promise.resolve()
    .then(() => {
      const pkgJsonFile = path.join(process.cwd(), project.folder, 'package.json');
      const pkgJson = require(pkgJsonFile);

      tools.logTitle('Updating package version');
      pkgJson.version = newVersion;

      if (!dryRun) {
        tools.writeJsonFileSync(pkgJsonFile, pkgJson);
      }

      tools.logSuccess(newVersion);
    })
    .catch((e) => {
      throw e;
    })
}
