"use strict";

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

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

function _path() {
  const data = _interopRequireDefault(require("path"));

  _path = function () {
    return data;
  };

  return data;
}

function _glob() {
  const data = _interopRequireDefault(require("glob"));

  _glob = function () {
    return data;
  };

  return data;
}

function _bitId() {
  const data = require("../bit-id");

  _bitId = function () {
    return data;
  };

  return data;
}

function _constants() {
  const data = require("../constants");

  _constants = function () {
    return data;
  };

  return data;
}

function _exceptions() {
  const data = require("../scope/exceptions");

  _exceptions = function () {
    return data;
  };

  return data;
}

function _logger() {
  const data = _interopRequireDefault(require("../logger/logger"));

  _logger = function () {
    return data;
  };

  return data;
}

function getLatestVersion(bitId, componentsDir) {
  // $FlowFixMe
  if (bitId.hasVersion()) return bitId.version;
  const regexRemoveLatestVersion = new RegExp(`${_constants().LATEST_BIT_VERSION}$`);
  const relativePathWithoutVersion = bitId.toFullPath().replace(regexRemoveLatestVersion, '');

  const pathWithoutVersion = _path().default.join(componentsDir, relativePathWithoutVersion);

  const versionsDirs = _glob().default.sync('*', {
    cwd: pathWithoutVersion
  });

  if (!versionsDirs || !versionsDirs.length) {
    throw new (_exceptions().ComponentNotFound)(bitId.toString());
  }

  return Math.max(versionsDirs);
}

function componentResolver(componentId, mainFilePath, projectRoot = process.cwd()) {
  const bitId = _bitId().BitId.parse(componentId, true); // used for envs. components, all have a scope


  const componentsDir = _path().default.join(projectRoot, _constants().BITS_DIRNAME);

  const version = getLatestVersion(bitId, componentsDir);
  const bitIdWithLatestVersion = bitId.changeVersion(version.toString());

  const componentPath = _path().default.join(componentsDir, bitIdWithLatestVersion.toFullPath());

  _logger().default.debug(`resolving component, path: ${componentPath}`);

  if (mainFilePath) {
    return _path().default.join(componentPath, mainFilePath);
  }

  return componentPath;
}

var _default = componentResolver;
exports.default = _default;