"use strict";

var _mapInstanceProperty2 = require("@babel/runtime-corejs3/core-js-stable/instance/map");

var _Object$defineProperty = require("@babel/runtime-corejs3/core-js-stable/object/define-property");

var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");

_Object$defineProperty(exports, "__esModule", {
  value: true
});

exports.default = _default;

var _indexOf = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/index-of"));

var _sort = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/sort"));

var _includes = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/includes"));

var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/map"));

var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/filter"));

var _startsWith = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/starts-with"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/asyncToGenerator"));

var _axios = _interopRequireDefault(require("axios"));

var _lodash = require("lodash");

var _semver = _interopRequireDefault(require("semver"));

var _run = _interopRequireDefault(require("./run"));

var _getApiKey = _interopRequireDefault(require("./getApiKey"));

const request = /*#__PURE__*/function () {
  var _ref = (0, _asyncToGenerator2.default)(function* (packageName, version, repo = 'internal-nuget-artifacts', apiKey = null) {
    const isNpm = (0, _indexOf.default)(repo).call(repo, 'npm') > -1;
    const path = isNpm ? `.npm/${packageName}` : packageName;
    const versionSep = isNpm ? '-' : '.';
    const data = 'internal-nuget-artifacts:' + (0, _getApiKey.default)(apiKey);
    const buff = new Buffer(data);
    const base64data = buff.toString('base64');
    return yield _axios.default.post('https://artifactory.meniga.net/artifactory/api/search/aql?', `items.find({
			"$and":[
				{"repo":"${repo}"},
				{"path": "${path}" },
				{"name": { "$match": "${packageName}${versionSep}${version}*"} }
			]
		})
		.include("name", "path", "repo")`, {
      headers: {
        Authorization: 'Basic ' + base64data,
        'content-type': 'text/plain'
      }
    }).then(response => response.data.results).catch(error => console.log('error', error.response));
  });

  return function request(_x, _x2) {
    return _ref.apply(this, arguments);
  };
}();

const getPrereleaseVersion = /*#__PURE__*/function () {
  var _ref2 = (0, _asyncToGenerator2.default)(function* (packageName, version, repo, apiKey) {
    const results = yield request(packageName, version, repo, apiKey);
    const packageVersions = (0, _mapInstanceProperty2(_lodash))(results, item => item.name.replace(packageName + '.', '').replace(packageName + '-', '').replace('.nupkg', '').replace('.json', '').replace('-RC', '-rc.').replace('-NEXT', '-next.'));
    const latestVersion = (0, _sort.default)(packageVersions).call(packageVersions, _semver.default.rcompare)[0] || version;
    return _semver.default.inc(latestVersion, 'prerelease');
  });

  return function getPrereleaseVersion(_x3, _x4, _x5, _x6) {
    return _ref2.apply(this, arguments);
  };
}();

function _default(_x7, _x8, _x9, _x10, _x11) {
  return _ref3.apply(this, arguments);
}

function _ref3() {
  _ref3 = (0, _asyncToGenerator2.default)(function* (packageName, version, branch, repo, apiKey, allowRelease = false) {
    let versionAdjusted = '';

    if (branch === 'develop') {
      versionAdjusted = yield getPrereleaseVersion(packageName, _semver.default.inc(version, 'minor') + '-next', repo, apiKey);
    } else if (branch === 'master') {
      versionAdjusted = version;
    } else if ((0, _includes.default)(branch).call(branch, 'release/')) {
      var _context, _context2;

      if (allowRelease === true) {
        // if there is a tag on the commit then just return the tag
        const headTag = (yield (0, _run.default)('git tag --contains')).split('\n');
        console.log('headTags', headTag);

        if (headTag.length > 0) {
          console.log('Got a head tag - parsing ' + headTag[0]);

          const v = _semver.default.parse(headTag[0]);

          if (v !== null && v.version === version) {
            console.log('Head tag matches package v, using that.');
            console.log('Version chosen ' + v.version);
            return v.version;
          }
        }
      }

      const branchVersion = _semver.default.coerce(branch.replace('release/', '').replace(packageName + '/', ''));

      const major = _semver.default.major(branchVersion);

      const minor = _semver.default.minor(branchVersion);

      yield (0, _run.default)('git fetch --tags', false, true, {
        stdio: 'inherit'
      });
      const tags = (yield (0, _run.default)('git tag -l')).split('\n');
      console.log('tags', tags);
      const patchNumbers = (0, _sort.default)(_context = (0, _map.default)(_context2 = (0, _filter.default)(tags).call(tags, item => (0, _startsWith.default)(item).call(item, `${major}.${minor}`))).call(_context2, item => _semver.default.patch(item))).call(_context);
      console.log('patchNumbers', patchNumbers);
      let newVersion = `${major}.${minor}.0`;

      if (patchNumbers.length > 0) {
        const latestPatch = patchNumbers[patchNumbers.length - 1];
        newVersion = _semver.default.inc(`${major}.${minor}.${latestPatch}`, 'patch');
      }

      versionAdjusted = yield getPrereleaseVersion(packageName, newVersion + '-rc', repo, apiKey);
    } else if ((0, _includes.default)(branch).call(branch, 'feature/')) {
      versionAdjusted = yield getPrereleaseVersion(packageName, _semver.default.inc(version, 'minor') + '-' + branch.replace('feature/', '').replace(packageName + '/', ''), repo, apiKey);
    } else {
      throw new Error('Unknown branch');
    }

    return versionAdjusted;
  });
  return _ref3.apply(this, arguments);
}

module.exports = exports.default;