'use strict';

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

var _regenerator;

function _load_regenerator() {
  return _regenerator = _interopRequireDefault(require('babel-runtime/regenerator'));
}

var getComponentsToExport = function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee2(ids, consumer, remote) {
    var _this = this;

    var componentsList, exportPendingComponents, idsToExportP, idsToExport;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            componentsList = new (_componentsList || _load_componentsList()).default(consumer);

            if (!(!ids || !ids.length)) {
              _context2.next = 7;
              break;
            }

            _context2.next = 4;
            return componentsList.listExportPendingComponentsIds();

          case 4:
            exportPendingComponents = _context2.sent;

            if (exportPendingComponents.length > 1) (_loader || _load_loader()).default.start((_loaderMessages || _load_loaderMessages()).BEFORE_EXPORTS);else (_loader || _load_loader()).default.start((_loaderMessages || _load_loaderMessages()).BEFORE_EXPORT);
            return _context2.abrupt('return', exportPendingComponents);

          case 7:
            idsToExportP = ids.map(function () {
              var _ref2 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee(id) {
                var parsedId, status;
                return (_regenerator || _load_regenerator()).default.wrap(function _callee$(_context) {
                  while (1) {
                    switch (_context.prev = _context.next) {
                      case 0:
                        parsedId = consumer.getParsedId(id);
                        _context.next = 3;
                        return consumer.getComponentStatusById(parsedId);

                      case 3:
                        status = _context.sent;

                        if (!(!status.staged && parsedId.scope === remote)) {
                          _context.next = 6;
                          break;
                        }

                        throw new (_idExportedAlready || _load_idExportedAlready()).default(parsedId.toString(), remote);

                      case 6:
                        return _context.abrupt('return', parsedId);

                      case 7:
                      case 'end':
                        return _context.stop();
                    }
                  }
                }, _callee, _this);
              }));

              return function (_x4) {
                return _ref2.apply(this, arguments);
              };
            }());

            (_loader || _load_loader()).default.start((_loaderMessages || _load_loaderMessages()).BEFORE_EXPORT); // show single export
            _context2.next = 11;
            return Promise.all(idsToExportP);

          case 11:
            idsToExport = _context2.sent;
            return _context2.abrupt('return', (_bitId || _load_bitId()).BitIds.fromArray(idsToExport));

          case 13:
          case 'end':
            return _context2.stop();
        }
      }
    }, _callee2, this);
  }));

  return function getComponentsToExport(_x, _x2, _x3) {
    return _ref.apply(this, arguments);
  };
}();

var addToBitJson = function () {
  var _ref3 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee4(ids, consumer) {
    var _this2 = this;

    var bitJsonDependencies, componentsIdsP;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            bitJsonDependencies = consumer.bitJson.getDependencies();
            componentsIdsP = ids.map(function () {
              var _ref4 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee3(componentId) {
                return (_regenerator || _load_regenerator()).default.wrap(function _callee3$(_context3) {
                  while (1) {
                    switch (_context3.prev = _context3.next) {
                      case 0:
                        if (!bitJsonDependencies.searchWithoutVersion(componentId)) {
                          _context3.next = 3;
                          break;
                        }

                        _context3.next = 3;
                        return consumer.bitJson.addDependency(componentId).write({ bitDir: consumer.getPath() });

                      case 3:
                        return _context3.abrupt('return', componentId);

                      case 4:
                      case 'end':
                        return _context3.stop();
                    }
                  }
                }, _callee3, _this2);
              }));

              return function (_x7) {
                return _ref4.apply(this, arguments);
              };
            }());
            return _context4.abrupt('return', Promise.all(componentsIdsP));

          case 3:
          case 'end':
            return _context4.stop();
        }
      }
    }, _callee4, this);
  }));

  return function addToBitJson(_x5, _x6) {
    return _ref3.apply(this, arguments);
  };
}();

var linkComponents = function () {
  var _ref5 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee5(ids, consumer) {
    var _ref6, components;

    return (_regenerator || _load_regenerator()).default.wrap(function _callee5$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            _context5.next = 2;
            return consumer.loadComponents(ids);

          case 2:
            _ref6 = _context5.sent;
            components = _ref6.components;

            (0, (_links || _load_links()).linkComponentsToNodeModules)(components, consumer);

          case 5:
          case 'end':
            return _context5.stop();
        }
      }
    }, _callee5, this);
  }));

  return function linkComponents(_x8, _x9) {
    return _ref5.apply(this, arguments);
  };
}();

var _ramda;

function _load_ramda() {
  return _ramda = _interopRequireDefault(require('ramda'));
}

var _consumer;

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

var _componentsList;

function _load_componentsList() {
  return _componentsList = _interopRequireDefault(require('../../../consumer/component/components-list'));
}

var _loader;

function _load_loader() {
  return _loader = _interopRequireDefault(require('../../../cli/loader'));
}

var _loaderMessages;

function _load_loaderMessages() {
  return _loaderMessages = require('../../../cli/loader/loader-messages');
}

var _bitId;

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

var _idExportedAlready;

function _load_idExportedAlready() {
  return _idExportedAlready = _interopRequireDefault(require('./exceptions/id-exported-already'));
}

var _links;

function _load_links() {
  return _links = require('../../../links');
}

var _logger;

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

var _analytics;

function _load_analytics() {
  return _analytics = require('../../../analytics/analytics');
}

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

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

exports.default = function () {
  var _ref7 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee6(ids, remote, save, eject) {
    var consumer, idsToExport, componentsIds, ejectErr, results;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee6$(_context6) {
      while (1) {
        switch (_context6.prev = _context6.next) {
          case 0:
            _context6.next = 2;
            return (0, (_consumer || _load_consumer()).loadConsumer)();

          case 2:
            consumer = _context6.sent;
            _context6.next = 5;
            return getComponentsToExport(ids, consumer, remote);

          case 5:
            idsToExport = _context6.sent;

            if (!(_ramda || _load_ramda()).default.isEmpty(idsToExport)) {
              _context6.next = 8;
              break;
            }

            return _context6.abrupt('return', []);

          case 8:
            _context6.next = 10;
            return consumer.scope.exportMany(idsToExport, remote, undefined, eject);

          case 10:
            componentsIds = _context6.sent;
            ejectErr = void 0;

            if (!eject) {
              _context6.next = 27;
              break;
            }

            _context6.prev = 13;
            _context6.next = 16;
            return consumer.eject(componentsIds);

          case 16:
            results = _context6.sent;
            _context6.next = 19;
            return consumer.onDestroy();

          case 19:
            return _context6.abrupt('return', results);

          case 22:
            _context6.prev = 22;
            _context6.t0 = _context6['catch'](13);

            (_logger || _load_logger()).default.error(_context6.t0);
            ejectErr = `The components ${componentsIds.map(function (c) {
              return c.toString();
            }).join(', ')} were exported successfully.
      However, the eject operation has failed due to an error: ${_context6.t0.msg || _context6.t0}`;
            // it might leave a damaged workspace behind. however, there are not much we can do to avoid
            // it. previously, in case of eject failure, we continued the linkComponent, but then, a new
            // bug introduced where bit-removed deleted directly imported dependencies, which fails
            // link-components afterwards and ended up having more confusion about the failure
            return _context6.abrupt('return', Promise.reject(ejectErr));

          case 27:
            if (!save) {
              _context6.next = 30;
              break;
            }

            _context6.next = 30;
            return addToBitJson(componentsIds, consumer);

          case 30:
            componentsIds.map(function (componentsId) {
              return consumer.bitMap.updateComponentId(componentsId);
            });
            _context6.next = 33;
            return linkComponents(componentsIds, consumer);

          case 33:
            (_analytics || _load_analytics()).Analytics.setExtraData('num_components', componentsIds.length);
            _context6.next = 36;
            return consumer.onDestroy();

          case 36:
            return _context6.abrupt('return', componentsIds);

          case 37:
          case 'end':
            return _context6.stop();
        }
      }
    }, _callee6, this, [[13, 22]]);
  }));

  function exportAction(_x10, _x11, _x12, _x13) {
    return _ref7.apply(this, arguments);
  }

  return exportAction;
}();