'use strict';

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

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

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


module.exports.getNewVersion = (
    pkg,
    commits,
    isSnapshot, isNextBranch, isSupportBranch, isHotfixBranch
  ) => {
  return Promise.resolve()
    .then(() => {
      return innerPackageCommon.getCurrentVersion(pkg);
    })

    .then((currentVersion) => {
      tools.logTitle('Extracting recommended version');

      tools.logInfo(`Current version found : ${currentVersion}`);

      const RELEASE_TYPES = ['major', 'minor', 'patch'];

      let newVersion = '1.0.0';

      if (commits) {

        tools.logInfo('Commits found for processing version, extracting...');

        let level = 2;
        let breakings = 0;
        let features = 0;

        commits.forEach((commit) => {
          if (commit.breakingChange) {
            breakings += commit.body;
            level = 1; // no major bump on "breaking changes"
          } else if (commit.type === 'feat') {
            features += 1;
            if (level === 2) {
              level = 1;
            }
          }
        });

        const release = {
          level: level,
          reason: 'There are ' + breakings + ' BREAKING CHANGES and ' + features + ' features',
          releaseType: RELEASE_TYPES[level]
        };

        tools.logInfo('release info found : ' + JSON.stringify(release));

        if (isNextBranch) {
          newVersion = semver.inc(currentVersion, 'prerelease');
        } else {
          newVersion = semver.valid(release.releaseType) || semver.inc(currentVersion, release.releaseType)
        }


      } else {
          tools.logInfo('No commits found for version processing...applying minor version upgrade');

          if (isNextBranch) {
            newVersion = semver.inc(currentVersion, 'prerelease');
          } else {
            newVersion = semver.inc(currentVersion, 'minor');
          }
      }

      tools.logInfo('probable new version : ' + newVersion);

      if (isSnapshot) {
        if (pkg.backend) {
          if (pkg.build && pkg.build.nodejs) {
            newVersion += '-snapshot-' + Date.now();
          } else {
            newVersion += '-SNAPSHOT';
          }
        } else {
          newVersion += '-snapshot-' + Date.now();
        }
      }

      if (isSupportBranch && pkg.backend) {
        newVersion = semver.inc(currentVersion, 'prerelease');
      }

      if (isHotfixBranch) {
        newVersion = semver.inc(currentVersion, 'prerelease');
      }

      tools.logSuccess('new version generated : ' + newVersion);

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




