'use strict';

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

var _regenerator;

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

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _ramda;

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

var _chalk;

function _load_chalk() {
  return _chalk = _interopRequireDefault(require('chalk'));
}

var _exceptions;

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

var _bitId;

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

var _component;

function _load_component() {
  return _component = _interopRequireDefault(require('../component'));
}

var _consumer;

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

var _scope;

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

var _loader;

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

var _loaderMessages;

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

var _logger;

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

var _utils;

function _load_utils() {
  return _utils = require('../../utils');
}

var _generalError;

function _load_generalError() {
  return _generalError = _interopRequireDefault(require('../../error/general-error'));
}

var _checkoutVersion;

function _load_checkoutVersion() {
  return _checkoutVersion = require('../versions-ops/checkout-version');
}

var _mergeVersion;

function _load_mergeVersion() {
  return _mergeVersion = require('../versions-ops/merge-version');
}

var _version;

function _load_version() {
  return _version = _interopRequireDefault(require('../../version'));
}

var _writeComponents;

function _load_writeComponents() {
  return _writeComponents = _interopRequireDefault(require('./write-components'));
}

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

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

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"); }); }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var ImportComponents = function () {
  function ImportComponents(consumer, options) {
    _classCallCheck(this, ImportComponents);

    this.consumer = consumer;
    this.options = options;
  }

  _createClass(ImportComponents, [{
    key: 'importComponents',
    value: function importComponents() {
      (_loader || _load_loader()).default.start((_loaderMessages || _load_loaderMessages()).BEFORE_IMPORT_ACTION);
      this.options.saveDependenciesAsComponents = this.consumer.bitJson.saveDependenciesAsComponents;
      if (!this.options.writePackageJson) {
        // if package.json is not written, it's impossible to install the packages and dependencies as npm packages
        this.options.installNpmPackages = false;
        this.options.saveDependenciesAsComponents = true;
      }
      if (!this.options.ids || (_ramda || _load_ramda()).default.isEmpty(this.options.ids)) {
        return this.importAccordingToBitJsonAndBitMap();
      }
      return this.importSpecificComponents();
    }
  }, {
    key: 'importSpecificComponents',
    value: function () {
      var _ref = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee() {
        var bitIds, beforeImportVersions, componentsWithDependencies, importDetails;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                // $FlowFixMe - we make sure the ids are populated before.
                (_logger || _load_logger()).default.debug(`importSpecificComponents, Ids: ${this.options.ids.join(', ')}`);
                // $FlowFixMe - we check if there are bitIds before we call this function
                bitIds = this.options.ids.map(function (raw) {
                  return (_bitId || _load_bitId()).BitId.parse(raw);
                });
                _context.next = 4;
                return this._getCurrentVersions(bitIds);

              case 4:
                beforeImportVersions = _context.sent;
                _context.next = 7;
                return this._warnForModifiedOrNewComponents(bitIds);

              case 7:
                _context.next = 9;
                return this.consumer.scope.getManyWithAllVersions(bitIds, false);

              case 9:
                componentsWithDependencies = _context.sent;
                _context.next = 12;
                return this._writeToFileSystem(componentsWithDependencies);

              case 12:
                _context.next = 14;
                return this._getImportDetails(beforeImportVersions, componentsWithDependencies);

              case 14:
                importDetails = _context.sent;
                return _context.abrupt('return', { dependencies: componentsWithDependencies, importDetails });

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

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

      return importSpecificComponents;
    }()
  }, {
    key: 'importAccordingToBitJsonAndBitMap',
    value: function () {
      var _ref2 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee2() {
        var dependenciesFromBitJson, componentsFromBitMap, compiler, tester, allDependenciesIds, beforeImportVersions, componentsAndDependenciesBitJson, componentsAndDependenciesBitMap, componentsAndDependencies, importDetails, envsPromises, envComponents;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                this.options.objectsOnly = !this.options.merge && !this.options.override;

                dependenciesFromBitJson = (_bitId || _load_bitId()).BitIds.fromObject(this.consumer.bitJson.dependencies);
                componentsFromBitMap = this.consumer.bitMap.getAuthoredExportedComponents();
                _context2.next = 5;
                return this.consumer.compiler;

              case 5:
                compiler = _context2.sent;
                _context2.next = 8;
                return this.consumer.tester;

              case 8:
                tester = _context2.sent;

                if (!(((_ramda || _load_ramda()).default.isNil(dependenciesFromBitJson) || (_ramda || _load_ramda()).default.isEmpty(dependenciesFromBitJson)) && (_ramda || _load_ramda()).default.isEmpty(componentsFromBitMap))) {
                  _context2.next = 16;
                  break;
                }

                if (this.options.withEnvironments) {
                  _context2.next = 14;
                  break;
                }

                return _context2.abrupt('return', Promise.reject(new (_exceptions || _load_exceptions()).NothingToImport()));

              case 14:
                if (!(!tester && !compiler)) {
                  _context2.next = 16;
                  break;
                }

                return _context2.abrupt('return', Promise.reject(new (_exceptions || _load_exceptions()).NothingToImport()));

              case 16:
                allDependenciesIds = dependenciesFromBitJson.concat(componentsFromBitMap);
                _context2.next = 19;
                return this._warnForModifiedOrNewComponents(allDependenciesIds);

              case 19:
                _context2.next = 21;
                return this._getCurrentVersions(allDependenciesIds);

              case 21:
                beforeImportVersions = _context2.sent;
                componentsAndDependenciesBitJson = [];
                componentsAndDependenciesBitMap = [];

                if (!dependenciesFromBitJson) {
                  _context2.next = 30;
                  break;
                }

                _context2.next = 27;
                return this.consumer.scope.getManyWithAllVersions(dependenciesFromBitJson, false);

              case 27:
                componentsAndDependenciesBitJson = _context2.sent;
                _context2.next = 30;
                return this._writeToFileSystem(componentsAndDependenciesBitJson);

              case 30:
                if (!componentsFromBitMap.length) {
                  _context2.next = 38;
                  break;
                }

                _context2.next = 33;
                return this.consumer.scope.getManyWithAllVersions(componentsFromBitMap, false);

              case 33:
                componentsAndDependenciesBitMap = _context2.sent;

                // don't write the package.json for an authored component, because its dependencies probably managed by the root
                // package.json. Also, don't install npm packages for the same reason.
                this.options.writePackageJson = false;
                this.options.installNpmPackages = false;
                // don't force the writing to the filesystem because as an author I may have some modified files
                _context2.next = 38;
                return this._writeToFileSystem(componentsAndDependenciesBitMap);

              case 38:
                componentsAndDependencies = [].concat(_toConsumableArray(componentsAndDependenciesBitJson), _toConsumableArray(componentsAndDependenciesBitMap));
                _context2.next = 41;
                return this._getImportDetails(beforeImportVersions, componentsAndDependencies);

              case 41:
                importDetails = _context2.sent;

                if (!this.options.withEnvironments) {
                  _context2.next = 50;
                  break;
                }

                envsPromises = [];

                if (compiler) {
                  envsPromises.push(compiler.install(this.consumer.scope, { verbose: this.options.verbose }));
                }
                if (tester) {
                  envsPromises.push(tester.install(this.consumer.scope, { verbose: this.options.verbose }));
                }
                _context2.next = 48;
                return Promise.all(envsPromises);

              case 48:
                envComponents = _context2.sent;
                return _context2.abrupt('return', {
                  dependencies: componentsAndDependencies,
                  envComponents,
                  importDetails
                });

              case 50:
                return _context2.abrupt('return', { dependencies: componentsAndDependencies, importDetails });

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

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

      return importAccordingToBitJsonAndBitMap;
    }()
  }, {
    key: '_getCurrentVersions',
    value: function () {
      var _ref3 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee4(ids) {
        var _this = this;

        var versionsP, versions;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                versionsP = ids.map(function () {
                  var _ref4 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee3(id) {
                    var modelComponent, idStr;
                    return (_regenerator || _load_regenerator()).default.wrap(function _callee3$(_context3) {
                      while (1) {
                        switch (_context3.prev = _context3.next) {
                          case 0:
                            _context3.next = 2;
                            return _this.consumer.scope.getModelComponentIfExist(id);

                          case 2:
                            modelComponent = _context3.sent;
                            idStr = id.toStringWithoutVersion();

                            if (modelComponent) {
                              _context3.next = 6;
                              break;
                            }

                            return _context3.abrupt('return', [idStr, []]);

                          case 6:
                            return _context3.abrupt('return', [idStr, modelComponent.listVersions()]);

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

                  return function (_x2) {
                    return _ref4.apply(this, arguments);
                  };
                }());
                _context4.next = 3;
                return Promise.all(versionsP);

              case 3:
                versions = _context4.sent;
                return _context4.abrupt('return', (_ramda || _load_ramda()).default.fromPairs(versions));

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

      function _getCurrentVersions(_x) {
        return _ref3.apply(this, arguments);
      }

      return _getCurrentVersions;
    }()

    /**
     * get import details, includes the diff between the versions array before import and after import
     */

  }, {
    key: '_getImportDetails',
    value: function () {
      var _ref5 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee6(currentVersions, components) {
        var _this2 = this;

        var detailsP;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                detailsP = components.map(function () {
                  var _ref6 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee5(component) {
                    var id, idStr, beforeImportVersions, modelComponent, afterImportVersions, versionDifference, getStatus, filesStatus;
                    return (_regenerator || _load_regenerator()).default.wrap(function _callee5$(_context5) {
                      while (1) {
                        switch (_context5.prev = _context5.next) {
                          case 0:
                            id = component.component.id;
                            idStr = id.toStringWithoutVersion();
                            beforeImportVersions = currentVersions[idStr];
                            _context5.next = 5;
                            return _this2.consumer.scope.getModelComponentIfExist(id);

                          case 5:
                            modelComponent = _context5.sent;

                            if (modelComponent) {
                              _context5.next = 8;
                              break;
                            }

                            throw new (_generalError || _load_generalError()).default(`imported component ${idStr} was not found in the model`);

                          case 8:
                            afterImportVersions = modelComponent.listVersions();
                            versionDifference = (_ramda || _load_ramda()).default.difference(afterImportVersions, beforeImportVersions);

                            getStatus = function getStatus() {
                              if (!versionDifference.length) return 'up to date';
                              if (!beforeImportVersions.length) return 'added';
                              return 'updated';
                            };

                            filesStatus = _this2.mergeStatus && _this2.mergeStatus[idStr] ? _this2.mergeStatus[idStr] : null;
                            return _context5.abrupt('return', { id: idStr, versions: versionDifference, status: getStatus(), filesStatus });

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

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

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

      function _getImportDetails(_x3, _x4) {
        return _ref5.apply(this, arguments);
      }

      return _getImportDetails;
    }()
  }, {
    key: '_warnForModifiedOrNewComponents',
    value: function () {
      var _ref7 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee7(ids) {
        var _this3 = this;

        var modifiedComponents;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee7$(_context7) {
          while (1) {
            switch (_context7.prev = _context7.next) {
              case 0:
                if (!(this.options.override || this.options.objectsOnly || this.options.merge)) {
                  _context7.next = 2;
                  break;
                }

                return _context7.abrupt('return', Promise.resolve());

              case 2:
                _context7.next = 4;
                return (0, (_utils || _load_utils()).filterAsync)(ids, function (id) {
                  return _this3.consumer.getComponentStatusById(id).then(function (status) {
                    return status.modified || status.newlyCreated;
                  });
                });

              case 4:
                modifiedComponents = _context7.sent;

                if (!modifiedComponents.length) {
                  _context7.next = 7;
                  break;
                }

                throw new (_generalError || _load_generalError()).default((_chalk || _load_chalk()).default.yellow(`unable to import the following components due to local changes, use --override flag to override your local changes\n${modifiedComponents.join('\n')} `));

              case 7:
                return _context7.abrupt('return', Promise.resolve());

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

      function _warnForModifiedOrNewComponents(_x6) {
        return _ref7.apply(this, arguments);
      }

      return _warnForModifiedOrNewComponents;
    }()
  }, {
    key: '_getMergeStatus',
    value: function () {
      var _ref8 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee8(componentWithDependencies) {
        var component, componentStatus, mergeStatus, componentModel, existingBitMapId, existingBitMapBitId, fsComponent, currentlyUsedVersion, baseComponent, currentComponent, mergeResults;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee8$(_context8) {
          while (1) {
            switch (_context8.prev = _context8.next) {
              case 0:
                component = componentWithDependencies.component;
                _context8.next = 3;
                return this.consumer.getComponentStatusById(component.id);

              case 3:
                componentStatus = _context8.sent;
                mergeStatus = { componentWithDependencies, mergeResults: null };

                if (componentStatus.modified) {
                  _context8.next = 7;
                  break;
                }

                return _context8.abrupt('return', mergeStatus);

              case 7:
                _context8.next = 9;
                return this.consumer.scope.sources.get(component.id);

              case 9:
                componentModel = _context8.sent;

                if (componentModel) {
                  _context8.next = 12;
                  break;
                }

                throw new (_generalError || _load_generalError()).default(`component ${component.id.toString()} wasn't found in the model`);

              case 12:
                existingBitMapId = this.consumer.bitMap.getExistingComponentId(component.id.toStringWithoutVersion());
                existingBitMapBitId = (_bitId || _load_bitId()).BitId.parse(existingBitMapId);
                _context8.next = 16;
                return this.consumer.loadComponent(existingBitMapBitId);

              case 16:
                fsComponent = _context8.sent;
                currentlyUsedVersion = existingBitMapBitId.version;
                _context8.next = 20;
                return componentModel.loadVersion(currentlyUsedVersion, this.consumer.scope.objects);

              case 20:
                baseComponent = _context8.sent;
                _context8.next = 23;
                return componentModel.loadVersion(component.id.version, this.consumer.scope.objects);

              case 23:
                currentComponent = _context8.sent;
                _context8.next = 26;
                return (0, (_mergeVersion || _load_mergeVersion()).threeWayMerge)({
                  consumer: this.consumer,
                  otherComponent: fsComponent,
                  otherVersion: currentlyUsedVersion,
                  currentComponent,
                  currentVersion: component.id.version,
                  baseComponent
                });

              case 26:
                mergeResults = _context8.sent;

                mergeStatus.mergeResults = mergeResults;
                return _context8.abrupt('return', mergeStatus);

              case 29:
              case 'end':
                return _context8.stop();
            }
          }
        }, _callee8, this);
      }));

      function _getMergeStatus(_x7) {
        return _ref8.apply(this, arguments);
      }

      return _getMergeStatus;
    }()

    /**
     * 1) when there are conflicts and the strategy is "ours", don't write the imported component to
     * the filesystem, only update bitmap.
     *
     * 2) when there are conflicts and the strategy is "theirs", override the local changes by the
     * imported component. (similar to --override)
     *
     * 3) when there is no conflict or there are conflicts and the strategy is manual, write the files
     * according to the merge result. (done by applyModifiedVersion())
     */

  }, {
    key: '_updateComponentFilesPerMergeStrategy',
    value: function () {
      var _ref9 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee9(componentMergeStatus) {
        var mergeResults, component, files, filesStatus;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee9$(_context9) {
          while (1) {
            switch (_context9.prev = _context9.next) {
              case 0:
                mergeResults = componentMergeStatus.mergeResults;

                if (mergeResults) {
                  _context9.next = 3;
                  break;
                }

                return _context9.abrupt('return', null);

              case 3:
                component = componentMergeStatus.componentWithDependencies.component;
                files = component.files;
                filesStatus = {};

                if (!(mergeResults.hasConflicts && this.options.mergeStrategy === (_mergeVersion || _load_mergeVersion()).MergeOptions.ours)) {
                  _context9.next = 11;
                  break;
                }

                // don't write the files to the filesystem, only bump the bitmap version.
                files.forEach(function (file) {
                  filesStatus[(0, (_utils || _load_utils()).pathNormalizeToLinux)(file.relative)] = (_mergeVersion || _load_mergeVersion()).FileStatus.unchanged;
                });
                this.consumer.bitMap.updateComponentId(component.id);
                this.consumer.bitMap.hasChanged = true;
                return _context9.abrupt('return', filesStatus);

              case 11:
                if (!(mergeResults.hasConflicts && this.options.mergeStrategy === (_mergeVersion || _load_mergeVersion()).MergeOptions.theirs)) {
                  _context9.next = 14;
                  break;
                }

                // the local changes will be overridden (as if the user entered --override flag for this component)
                files.forEach(function (file) {
                  filesStatus[(0, (_utils || _load_utils()).pathNormalizeToLinux)(file.relative)] = (_mergeVersion || _load_mergeVersion()).FileStatus.updated;
                });
                return _context9.abrupt('return', filesStatus);

              case 14:
                return _context9.abrupt('return', (0, (_checkoutVersion || _load_checkoutVersion()).applyModifiedVersion)(component.files, mergeResults, this.options.mergeStrategy));

              case 15:
              case 'end':
                return _context9.stop();
            }
          }
        }, _callee9, this);
      }));

      function _updateComponentFilesPerMergeStrategy(_x8) {
        return _ref9.apply(this, arguments);
      }

      return _updateComponentFilesPerMergeStrategy;
    }()

    /**
     * update the component files if they are modified and there is a merge strategy.
     * returns only the components that need to be written to the filesystem
     */

  }, {
    key: 'updateAllComponentsAccordingToMergeStrategy',
    value: function () {
      var _ref10 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee11(componentsWithDependencies) {
        var _this4 = this;

        var componentsStatusP, componentsStatus, componentWithConflict, componentsToWriteP, componentsToWrite, removeNulls;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee11$(_context11) {
          while (1) {
            switch (_context11.prev = _context11.next) {
              case 0:
                if (this.options.merge) {
                  _context11.next = 2;
                  break;
                }

                return _context11.abrupt('return', componentsWithDependencies);

              case 2:
                componentsStatusP = componentsWithDependencies.map(function (componentWithDependencies) {
                  return _this4._getMergeStatus(componentWithDependencies);
                });
                _context11.next = 5;
                return Promise.all(componentsStatusP);

              case 5:
                componentsStatus = _context11.sent;
                componentWithConflict = componentsStatus.find(function (component) {
                  return component.mergeResults && component.mergeResults.hasConflicts;
                });

                if (!(componentWithConflict && !this.options.mergeStrategy)) {
                  _context11.next = 11;
                  break;
                }

                _context11.next = 10;
                return (0, (_mergeVersion || _load_mergeVersion()).getMergeStrategyInteractive)();

              case 10:
                this.options.mergeStrategy = _context11.sent;

              case 11:
                this.mergeStatus = {};

                componentsToWriteP = componentsStatus.map(function () {
                  var _ref11 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee10(componentStatus) {
                    var filesStatus, componentWithDependencies, unchangedFiles;
                    return (_regenerator || _load_regenerator()).default.wrap(function _callee10$(_context10) {
                      while (1) {
                        switch (_context10.prev = _context10.next) {
                          case 0:
                            _context10.next = 2;
                            return _this4._updateComponentFilesPerMergeStrategy(componentStatus);

                          case 2:
                            filesStatus = _context10.sent;
                            componentWithDependencies = componentStatus.componentWithDependencies;

                            if (filesStatus) {
                              _context10.next = 6;
                              break;
                            }

                            return _context10.abrupt('return', componentWithDependencies);

                          case 6:
                            _this4.mergeStatus[componentWithDependencies.component.id.toStringWithoutVersion()] = filesStatus;
                            unchangedFiles = Object.keys(filesStatus).filter(function (file) {
                              return filesStatus[file] === (_mergeVersion || _load_mergeVersion()).FileStatus.unchanged;
                            });

                            if (!(unchangedFiles.length === Object.keys(filesStatus).length)) {
                              _context10.next = 10;
                              break;
                            }

                            return _context10.abrupt('return', null);

                          case 10:
                            return _context10.abrupt('return', componentWithDependencies);

                          case 11:
                          case 'end':
                            return _context10.stop();
                        }
                      }
                    }, _callee10, _this4);
                  }));

                  return function (_x10) {
                    return _ref11.apply(this, arguments);
                  };
                }());
                _context11.next = 15;
                return Promise.all(componentsToWriteP);

              case 15:
                componentsToWrite = _context11.sent;
                removeNulls = (_ramda || _load_ramda()).default.reject((_ramda || _load_ramda()).default.isNil);
                return _context11.abrupt('return', removeNulls(componentsToWrite));

              case 18:
              case 'end':
                return _context11.stop();
            }
          }
        }, _callee11, this);
      }));

      function updateAllComponentsAccordingToMergeStrategy(_x9) {
        return _ref10.apply(this, arguments);
      }

      return updateAllComponentsAccordingToMergeStrategy;
    }()
  }, {
    key: '_writeToFileSystem',
    value: function () {
      var _ref12 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee12(componentsWithDependencies) {
        var componentsToWrite;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee12$(_context12) {
          while (1) {
            switch (_context12.prev = _context12.next) {
              case 0:
                if (!this.options.objectsOnly) {
                  _context12.next = 2;
                  break;
                }

                return _context12.abrupt('return');

              case 2:
                _context12.next = 4;
                return this.updateAllComponentsAccordingToMergeStrategy(componentsWithDependencies);

              case 4:
                componentsToWrite = _context12.sent;
                _context12.next = 7;
                return (0, (_writeComponents || _load_writeComponents()).default)({
                  consumer: this.consumer,
                  componentsWithDependencies: componentsToWrite,
                  writeToPath: this.options.writeToPath,
                  writePackageJson: this.options.writePackageJson,
                  writeBitJson: this.options.writeBitJson,
                  writeDists: this.options.writeDists,
                  installNpmPackages: this.options.installNpmPackages,
                  saveDependenciesAsComponents: this.options.saveDependenciesAsComponents,
                  verbose: this.options.verbose,
                  override: this.options.override
                });

              case 7:
              case 'end':
                return _context12.stop();
            }
          }
        }, _callee12, this);
      }));

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

      return _writeToFileSystem;
    }()
  }]);

  return ImportComponents;
}();

exports.default = ImportComponents;