"use strict";

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

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

function _bluebird() {
  const data = require("bluebird");

  _bluebird = function () {
    return data;
  };

  return data;
}

function _consumer() {
  const data = require("../../../consumer");

  _consumer = function () {
    return data;
  };

  return data;
}

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

  _scope = function () {
    return data;
  };

  return data;
}

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

  _exceptions = function () {
    return data;
  };

  return data;
}

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

  _logger = function () {
    return data;
  };

  return data;
}

function buildInScope({
  id,
  save,
  verbose,
  scopePath,
  directory,
  keep,
  noCache = false
}) {
  _logger().default.debugAndAddBreadCrumb('buildInScope', 'id: {id}, scopePath: {scopePath}', {
    id,
    scopePath
  });

  function loadFromScope(_x) {
    return _loadFromScope.apply(this, arguments);
  }

  function _loadFromScope() {
    _loadFromScope = (0, _bluebird().coroutine)(function* (initialError) {
      const getScope =
      /*#__PURE__*/
      function () {
        var _ref = (0, _bluebird().coroutine)(function* () {
          try {
            const scope = yield (0, _scope().loadScope)(scopePath || process.cwd());
            return scope;
          } catch (err) {
            throw new Error(initialError || err);
          }
        });

        return function getScope() {
          return _ref.apply(this, arguments);
        };
      }();

      const scope = yield getScope();
      const bitId = yield scope.getParsedId(id);
      return scope.build({
        bitId,
        save,
        verbose,
        directory,
        keep,
        noCache
      });
    });
    return _loadFromScope.apply(this, arguments);
  }

  function loadFromConsumer() {
    return (0, _consumer().loadConsumer)().then(consumer => {
      const bitId = consumer.getParsedId(id);
      return consumer.scope.build({
        bitId,
        save,
        consumer,
        verbose
      });
    });
  }

  if (scopePath) return loadFromScope();
  return loadFromConsumer().catch(err => {
    if (!(err instanceof _exceptions().ConsumerNotFound)) throw err;
    return loadFromScope(err);
  });
}