'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 _manyComponentsWriter;

function _load_manyComponentsWriter() {
  return _manyComponentsWriter = _interopRequireDefault(require('./many-components-writer'));
}

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.scope = consumer.scope;
    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, true);
                }); // we don't support importing without a scope name

                _context.next = 4;
                return this._getCurrentVersions(bitIds);

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

              case 7:
                _context.next = 9;
                return this.consumer.importComponents(bitIds, true);

              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, context, _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();
                compiler = void 0;
                tester = void 0;

                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 = 8;
                  break;
                }

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

              case 8:
                _context2.next = 10;
                return this.consumer.compiler;

              case 10:
                compiler = _context2.sent;
                _context2.next = 13;
                return this.consumer.tester;

              case 13:
                tester = _context2.sent;

                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._throwForModifiedOrNewComponents(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.importComponents(dependenciesFromBitJson, true);

              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.importComponents(componentsFromBitMap, true);

              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 = 63;
                  break;
                }

                _context2.t0 = compiler;

                if (_context2.t0) {
                  _context2.next = 48;
                  break;
                }

                _context2.next = 47;
                return this.consumer.compiler;

              case 47:
                _context2.t0 = _context2.sent;

              case 48:
                compiler = _context2.t0;
                _context2.t1 = tester;

                if (_context2.t1) {
                  _context2.next = 54;
                  break;
                }

                _context2.next = 53;
                return this.consumer.tester;

              case 53:
                _context2.t1 = _context2.sent;

              case 54:
                tester = _context2.t1;
                envsPromises = [];
                context = { workspaceDir: this.consumer.getPath() };

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

              case 61:
                _envComponents = _context2.sent;
                return _context2.abrupt('return', {
                  dependencies: componentsAndDependencies,
                  envComponents: (_ramda || _load_ramda()).default.flatten(_envComponents),
                  importDetails
                });

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

              case 64:
              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];

                            if (beforeImportVersions) {
                              _context5.next = 5;
                              break;
                            }

                            throw new Error(`_getImportDetails failed finding ${idStr} in currentVersions, which has ${Object.keys(currentVersions).join(', ')}`);

                          case 5:
                            _context5.next = 7;
                            return _this2.consumer.scope.getModelComponentIfExist(id);

                          case 7:
                            modelComponent = _context5.sent;

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

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

                          case 10:
                            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 15:
                          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: '_throwForPotentialIssues',
    value: function () {
      var _ref7 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee7(ids) {
        return (_regenerator || _load_regenerator()).default.wrap(function _callee7$(_context7) {
          while (1) {
            switch (_context7.prev = _context7.next) {
              case 0:
                _context7.next = 2;
                return this._throwForModifiedOrNewComponents(ids);

              case 2:
                this._throwForDifferentComponentWithSameName(ids);

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

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

      return _throwForPotentialIssues;
    }()
  }, {
    key: '_throwForModifiedOrNewComponents',
    value: function () {
      var _ref8 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee8(ids) {
        var _this3 = this;

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

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

              case 2:
                _context8.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 = _context8.sent;

                if (!modifiedComponents.length) {
                  _context8.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 _context8.abrupt('return', Promise.resolve());

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

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

      return _throwForModifiedOrNewComponents;
    }()

    /**
     * Model Component id() calculation uses id.toString() for the hash.
     * If an imported component has scope+name equals to a local name, both will have the exact same
     * hash and they'll override each other.
     */

  }, {
    key: '_throwForDifferentComponentWithSameName',
    value: function _throwForDifferentComponentWithSameName(ids) {
      var _this4 = this;

      ids.forEach(function (id) {
        var existingId = _this4.consumer.getParsedIdIfExist(id.toStringWithoutVersion());
        if (existingId && !existingId.hasScope()) {
          throw new (_generalError || _load_generalError()).default(`unable to import ${id.toString()}. the component name conflicted with your local component with the same name.
        it's fine to have components with the same name as long as their scope names are different.
        Make sure to export your component first to get a scope and then try importing again`);
        }
      });
    }
  }, {
    key: '_getMergeStatus',
    value: function () {
      var _ref9 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee9(componentWithDependencies) {
        var component, componentStatus, mergeStatus, componentModel, existingBitMapBitId, fsComponent, currentlyUsedVersion, baseComponent, currentComponent, mergeResults;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee9$(_context9) {
          while (1) {
            switch (_context9.prev = _context9.next) {
              case 0:
                component = componentWithDependencies.component;
                _context9.next = 3;
                return this.consumer.getComponentStatusById(component.id);

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

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

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

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

              case 9:
                componentModel = _context9.sent;

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

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

              case 12:
                existingBitMapBitId = this.consumer.bitMap.getBitId(component.id, { ignoreVersion: true });
                _context9.next = 15;
                return this.consumer.loadComponent(existingBitMapBitId);

              case 15:
                fsComponent = _context9.sent;
                currentlyUsedVersion = existingBitMapBitId.version;
                _context9.next = 19;
                return this.consumer.loadComponentFromModel(existingBitMapBitId);

              case 19:
                baseComponent = _context9.sent;
                _context9.next = 22;
                return this.consumer.loadComponentFromModel(component.id);

              case 22:
                currentComponent = _context9.sent;
                _context9.next = 25;
                return (0, (_mergeVersion || _load_mergeVersion()).threeWayMerge)({
                  consumer: this.consumer,
                  otherComponent: fsComponent,
                  otherVersion: currentlyUsedVersion,
                  currentComponent, // $FlowFixMe
                  currentVersion: component.id.version,
                  baseComponent
                });

              case 25:
                mergeResults = _context9.sent;

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

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

      function _getMergeStatus(_x8) {
        return _ref9.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 _ref10 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee10(componentMergeStatus) {
        var mergeResults, component, files, filesStatus;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee10$(_context10) {
          while (1) {
            switch (_context10.prev = _context10.next) {
              case 0:
                mergeResults = componentMergeStatus.mergeResults;

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

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

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

                if (!(mergeResults.hasConflicts && this.options.mergeStrategy === (_mergeVersion || _load_mergeVersion()).MergeOptions.ours)) {
                  _context10.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 _context10.abrupt('return', filesStatus);

              case 11:
                if (!(mergeResults.hasConflicts && this.options.mergeStrategy === (_mergeVersion || _load_mergeVersion()).MergeOptions.theirs)) {
                  _context10.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 _context10.abrupt('return', filesStatus);

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

              case 15:
              case 'end':
                return _context10.stop();
            }
          }
        }, _callee10, this);
      }));

      function _updateComponentFilesPerMergeStrategy(_x9) {
        return _ref10.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 _ref11 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee12(componentsWithDependencies) {
        var _this5 = this;

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

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

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

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

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

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

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

              case 11:
                this.mergeStatus = {};

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

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

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

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

                          case 6:
                            _this5.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)) {
                              _context11.next = 10;
                              break;
                            }

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

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

                          case 11:
                          case 'end':
                            return _context11.stop();
                        }
                      }
                    }, _callee11, _this5);
                  }));

                  return function (_x11) {
                    return _ref12.apply(this, arguments);
                  };
                }());
                _context12.next = 15;
                return Promise.all(componentsToWriteP);

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

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

      function updateAllComponentsAccordingToMergeStrategy(_x10) {
        return _ref11.apply(this, arguments);
      }

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

                return _context13.abrupt('return');

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

              case 4:
                componentsToWrite = _context13.sent;

                if (this.options.writeConfig && !this.options.configDir) {
                  this.options.configDir = this.consumer.dirStructure.ejectedEnvsDirStructure;
                }
                manyComponentsWriter = new (_manyComponentsWriter || _load_manyComponentsWriter()).default({
                  consumer: this.consumer,
                  componentsWithDependencies: componentsToWrite,
                  writeToPath: this.options.writeToPath,
                  writePackageJson: this.options.writePackageJson,
                  writeConfig: this.options.writeConfig,
                  configDir: this.options.configDir,
                  writeDists: this.options.writeDists,
                  installNpmPackages: this.options.installNpmPackages,
                  saveDependenciesAsComponents: this.options.saveDependenciesAsComponents,
                  verbose: this.options.verbose,
                  override: this.options.override
                });
                _context13.next = 9;
                return manyComponentsWriter.writeAll();

              case 9:
              case 'end':
                return _context13.stop();
            }
          }
        }, _callee13, this);
      }));

      function _writeToFileSystem(_x12) {
        return _ref13.apply(this, arguments);
      }

      return _writeToFileSystem;
    }()
  }]);

  return ImportComponents;
}();

exports.default = ImportComponents;