'use strict';

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

var _path;

function _load_path() {
  return _path = _interopRequireDefault(require('path'));
}

var _glob;

function _load_glob() {
  return _glob = _interopRequireDefault(require('glob'));
}

var _bitId;

function _load_bitId() {
  return _bitId = require('../bit-id');
}

var _constants;

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

var _exceptions;

function _load_exceptions() {
  return _exceptions = require('../scope/exceptions');
}

var _logger;

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

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

function getLatestVersion(bitId, componentsDir) {
  // $FlowFixMe
  if (bitId.hasVersion()) return bitId.version;
  var regexRemoveLatestVersion = new RegExp(`${(_constants || _load_constants()).LATEST_BIT_VERSION}$`);
  var relativePathWithoutVersion = bitId.toFullPath().replace(regexRemoveLatestVersion, '');
  var pathWithoutVersion = (_path || _load_path()).default.join(componentsDir, relativePathWithoutVersion);
  var versionsDirs = (_glob || _load_glob()).default.sync('*', { cwd: pathWithoutVersion });
  if (!versionsDirs || !versionsDirs.length) {
    throw new (_exceptions || _load_exceptions()).ComponentNotFound(bitId.toString());
  }
  return Math.max(versionsDirs);
}

function componentResolver(componentId, mainFilePath) {
  var projectRoot = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : process.cwd();

  var bitId = (_bitId || _load_bitId()).BitId.parse(componentId, true); // used for envs. components, all have a scope
  var componentsDir = (_path || _load_path()).default.join(projectRoot, (_constants || _load_constants()).BITS_DIRNAME);
  var version = getLatestVersion(bitId, componentsDir);
  var bitIdWithLatestVersion = bitId.changeVersion(version.toString());
  var componentPath = (_path || _load_path()).default.join(componentsDir, bitIdWithLatestVersion.toFullPath());
  (_logger || _load_logger()).default.debug(`resolving component, path: ${componentPath}`);
  if (mainFilePath) {
    return (_path || _load_path()).default.join(componentPath, mainFilePath);
  }
  return componentPath;
}

exports.default = componentResolver;