'use strict';

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

var _regenerator;

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

var exportComponents = function () {
  var _ref2 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee2(ids, remote, save) {
    var consumer, idsToExport, componentsIds;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            _context2.next = 2;
            return (0, (_consumer || _load_consumer()).loadConsumer)();

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

          case 5:
            idsToExport = _context2.sent;

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

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

          case 8:
            _context2.next = 10;
            return (0, (_exportScopeComponents || _load_exportScopeComponents()).exportMany)(consumer.scope, idsToExport, remote, undefined);

          case 10:
            componentsIds = _context2.sent;

            if (!save) {
              _context2.next = 14;
              break;
            }

            _context2.next = 14;
            return addToBitJson(componentsIds, consumer);

          case 14:
            componentsIds.map(function (componentsId) {
              return consumer.bitMap.updateComponentId(componentsId);
            });
            _context2.next = 17;
            return linkComponents(componentsIds, consumer);

          case 17:
            (_analytics || _load_analytics()).Analytics.setExtraData('num_components', componentsIds.length);
            // it is important to have consumer.onDestroy() before running the eject operation, we want the
            // export and eject operations to function independently. we don't want to lose the changes to
            // .bitmap file done by the export action in case the eject action has failed.
            _context2.next = 20;
            return consumer.onDestroy();

          case 20:
            return _context2.abrupt('return', componentsIds);

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

  return function exportComponents(_x5, _x6, _x7) {
    return _ref2.apply(this, arguments);
  };
}();

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

    var componentsList, idsHaveWildcard, exportPendingComponents, componentsToExport, loaderMsg, idsToExportP, idsToExport;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            componentsList = new (_componentsList || _load_componentsList()).default(consumer);
            idsHaveWildcard = (0, (_hasWildcard || _load_hasWildcard()).default)(ids);

            if (!(!ids || !ids.length || idsHaveWildcard)) {
              _context4.next = 11;
              break;
            }

            (_loader || _load_loader()).default.start((_loaderMessages || _load_loaderMessages()).BEFORE_LOADING_COMPONENTS);
            _context4.next = 6;
            return componentsList.listExportPendingComponentsIds();

          case 6:
            exportPendingComponents = _context4.sent;
            componentsToExport = idsHaveWildcard // $FlowFixMe ids are set at this point
            ? (_componentsList || _load_componentsList()).default.filterComponentsByWildcard(exportPendingComponents, ids) : exportPendingComponents;
            loaderMsg = componentsToExport.length > 1 ? (_loaderMessages || _load_loaderMessages()).BEFORE_EXPORTS : (_loaderMessages || _load_loaderMessages()).BEFORE_EXPORT;

            (_loader || _load_loader()).default.start(loaderMsg);
            return _context4.abrupt('return', componentsToExport);

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

                      case 3:
                        status = _context3.sent;

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

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

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

                      case 7:
                      case 'end':
                        return _context3.stop();
                    }
                  }
                }, _callee3, _this);
              }));

              return function (_x11) {
                return _ref4.apply(this, arguments);
              };
            }());

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

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

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

  return function getComponentsToExport(_x8, _x9, _x10) {
    return _ref3.apply(this, arguments);
  };
}();

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

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

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

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

                      case 4:
                      case 'end':
                        return _context5.stop();
                    }
                  }
                }, _callee5, _this2);
              }));

              return function (_x14) {
                return _ref6.apply(this, arguments);
              };
            }());
            return _context6.abrupt('return', Promise.all(componentsIdsP));

          case 3:
          case 'end':
            return _context6.stop();
        }
      }
    }, _callee6, this);
  }));

  return function addToBitJson(_x12, _x13) {
    return _ref5.apply(this, arguments);
  };
}();

var linkComponents = function () {
  var _ref7 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee7(ids, consumer) {
    var components, nodeModuleLinker;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee7$(_context7) {
      while (1) {
        switch (_context7.prev = _context7.next) {
          case 0:
            _context7.next = 2;
            return Promise.all(ids.map(function (id) {
              return consumer.loadComponentFromModel(id);
            }));

          case 2:
            components = _context7.sent;
            nodeModuleLinker = new (_links || _load_links()).NodeModuleLinker(components, consumer);
            _context7.next = 6;
            return nodeModuleLinker.link();

          case 6:
          case 'end':
            return _context7.stop();
        }
      }
    }, _callee7, this);
  }));

  return function linkComponents(_x15, _x16) {
    return _ref7.apply(this, arguments);
  };
}();

var ejectExportedComponents = function () {
  var _ref8 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee8(componentsIds) {
    var consumer, ejectResults, ejectComponents, ejectErr;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee8$(_context8) {
      while (1) {
        switch (_context8.prev = _context8.next) {
          case 0:
            _context8.next = 2;
            return (0, (_consumer || _load_consumer()).loadConsumer)();

          case 2:
            consumer = _context8.sent;
            ejectResults = void 0;
            _context8.prev = 4;
            ejectComponents = new (_ejectComponents || _load_ejectComponents()).default(consumer, componentsIds);
            _context8.next = 8;
            return ejectComponents.eject();

          case 8:
            ejectResults = _context8.sent;
            _context8.next = 16;
            break;

          case 11:
            _context8.prev = 11;
            _context8.t0 = _context8['catch'](4);

            (_logger || _load_logger()).default.error(_context8.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: ${_context8.t0.msg || _context8.t0}`;
            throw new Error(ejectErr);

          case 16:
            _context8.next = 18;
            return consumer.onDestroy();

          case 18:
            return _context8.abrupt('return', ejectResults);

          case 19:
          case 'end':
            return _context8.stop();
        }
      }
    }, _callee8, this, [[4, 11]]);
  }));

  return function ejectExportedComponents(_x17) {
    return _ref8.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 _logger;

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

var _analytics;

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

var _ejectComponents;

function _load_ejectComponents() {
  return _ejectComponents = _interopRequireDefault(require('../../../consumer/component-ops/eject-components'));
}

var _hasWildcard;

function _load_hasWildcard() {
  return _hasWildcard = _interopRequireDefault(require('../../../utils/string/has-wildcard'));
}

var _exportScopeComponents;

function _load_exportScopeComponents() {
  return _exportScopeComponents = require('../../../scope/component-ops/export-scope-components');
}

var _links;

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

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 _ref = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee(ids, remote, save, eject) {
    var componentsIds, ejectResults;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return exportComponents(ids, remote, save);

          case 2:
            componentsIds = _context.sent;
            ejectResults = void 0;

            if (!eject) {
              _context.next = 8;
              break;
            }

            _context.next = 7;
            return ejectExportedComponents(componentsIds);

          case 7:
            ejectResults = _context.sent;

          case 8:
            return _context.abrupt('return', { componentsIds, ejectResults });

          case 9:
          case 'end':
            return _context.stop();
        }
      }
    }, _callee, this);
  }));

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

  return exportAction;
}();