'use strict';

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

var _fsExtra;

function _load_fsExtra() {
  return _fsExtra = _interopRequireDefault(require('fs-extra'));
}

var _gitconfig;

function _load_gitconfig() {
  return _gitconfig = _interopRequireDefault(require('@teambit/gitconfig'));
}

var _yn;

function _load_yn() {
  return _yn = _interopRequireDefault(require('yn'));
}

var _globalConfig;

function _load_globalConfig() {
  return _globalConfig = _interopRequireWildcard(require('../../api/consumer/lib/global-config'));
}

var _constants;

function _load_constants() {
  return _constants = require('../../constants');
}

var _logger;

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

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

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

/**
 * Add more keys to the context which will be passed to hooks
 * @param {Object} context
 */
function enrichContextFromGlobal() {
  var context = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

  (_logger || _load_logger()).default.debug('enrich context from global config');
  var username = (_globalConfig || _load_globalConfig()).getSync((_constants || _load_constants()).CFG_USER_NAME_KEY);
  var email = (_globalConfig || _load_globalConfig()).getSync((_constants || _load_constants()).CFG_USER_EMAIL_KEY);
  var sshKeyFile = (_globalConfig || _load_globalConfig()).getSync((_constants || _load_constants()).CFG_SSH_KEY_FILE_KEY);
  var token = (_globalConfig || _load_globalConfig()).getSync((_constants || _load_constants()).CFG_USER_TOKEN_KEY);
  var pubSshKeyFile = sshKeyFile ? `${sshKeyFile}.pub` : undefined;
  var pubSshKey = _getSshPubKey(pubSshKeyFile);
  var repo = (0, (_yn || _load_yn()).default)((_globalConfig || _load_globalConfig()).getSync((_constants || _load_constants()).CFG_REPOSITORY_REPORTING_KEY), { default: true }) ? (_gitconfig || _load_gitconfig()).default.getUrl() : undefined;
  Object.assign(context, { username, email, pubSshKey, token, repo });
}

function _getSshPubKey() {
  var pubSshKeyFile = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : `${(_constants || _load_constants()).DEFAULT_SSH_KEY_FILE}.pub`;

  (_logger || _load_logger()).default.debug(`reading ssh public key from ${pubSshKeyFile}`);
  if (!(_fsExtra || _load_fsExtra()).default.pathExistsSync(pubSshKeyFile)) {
    return null;
  }
  var buf = (_fsExtra || _load_fsExtra()).default.readFileSync(pubSshKeyFile);
  return buf.toString();
}