'use strict';

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

var _consumer;

function _load_consumer() {
  return _consumer = require('../../../consumer');
}

var _bitId;

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

var _scope;

function _load_scope() {
  return _scope = require('../../../scope');
}

var _exceptions;

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

var _logger;

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

var _specsResults;

function _load_specsResults() {
  return _specsResults = _interopRequireDefault(require('../../../consumer/specs-results'));
}

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

function testInScope(_ref) {
  var id = _ref.id,
      save = _ref.save,
      verbose = _ref.verbose,
      scopePath = _ref.scopePath,
      directory = _ref.directory,
      keep = _ref.keep;

  (_logger || _load_logger()).default.debug(`testInScope, id: ${id}, scopePath: ${scopePath}`);
  function loadFromScope(initialError) {
    return (0, (_scope || _load_scope()).loadScope)(scopePath || process.cwd()).catch(function (newErr) {
      return Promise.reject(initialError || newErr);
    }).then(function (scope) {
      var bitId = (_bitId || _load_bitId()).BitId.parse(id);
      return scope.runComponentSpecs({
        bitId,
        save,
        verbose,
        isolated: true,
        directory,
        keep
      });
    }).catch(function (e) {
      return Promise.reject(e);
    });
  }

  function loadFromConsumer() {
    return (0, (_consumer || _load_consumer()).loadConsumer)().then(function (consumer) {
      var bitId = (_bitId || _load_bitId()).BitId.parse(id);
      return consumer.scope.runComponentSpecs({
        consumer,
        bitId,
        save,
        verbose,
        isolated: true
      });
    });
  }

  if (scopePath) return loadFromScope();

  return loadFromConsumer().catch(function (err) {
    if (!(err instanceof (_exceptions || _load_exceptions()).ConsumerNotFound)) throw err;
    return loadFromScope(err);
  });
}