'use strict';

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

var _regenerator;

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

var _bluebird;

function _load_bluebird() {
  return _bluebird = require('bluebird');
}

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

var _constants;

function _load_constants() {
  return _constants = require('../../constants');
}

var _hasWildcard;

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

var _consumer2;

function _load_consumer2() {
  return _consumer2 = require('../../api/consumer');
}

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 _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.config.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.importAccordingToBitMap();
      }
      return this.importSpecificComponents();
    }
  }, {
    key: 'importSpecificComponents',
    value: function () {
      var _ref = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__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:
                (_logger || _load_logger()).default.debug(`importSpecificComponents, Ids: ${this.options.ids.join(', ')}`);
                _context.next = 3;
                return this._getBitIds();

              case 3:
                bitIds = _context.sent;
                _context.next = 6;
                return this._getCurrentVersions(bitIds);

              case 6:
                beforeImportVersions = _context.sent;
                _context.next = 9;
                return this._throwForPotentialIssues(bitIds);

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

              case 11:
                componentsWithDependencies = _context.sent;
                _context.next = 14;
                return this._writeToFileSystem(componentsWithDependencies);

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

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

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

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

      return importSpecificComponents;
    }()
  }, {
    key: '_getBitIds',
    value: function () {
      var _ref2 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee3() {
        var _this = this;

        var bitIds;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                bitIds = [];
                _context3.next = 3;
                return Promise.all(this.options.ids.map(function () {
                  var _ref3 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee2(idStr) {
                    var idSplit, scopeName, namespacesUsingWildcards, listResult, _ids;

                    return (_regenerator || _load_regenerator()).default.wrap(function _callee2$(_context2) {
                      while (1) {
                        switch (_context2.prev = _context2.next) {
                          case 0:
                            if (!(0, (_hasWildcard || _load_hasWildcard()).default)(idStr)) {
                              _context2.next = 15;
                              break;
                            }

                            if (idStr.includes('/')) {
                              _context2.next = 3;
                              break;
                            }

                            throw new (_generalError || _load_generalError()).default(`import with wildcards expects full scope-name before the wildcards, instead, got "${idStr}"`);

                          case 3:
                            idSplit = idStr.split('/');
                            scopeName = idSplit[0];
                            namespacesUsingWildcards = (_ramda || _load_ramda()).default.tail(idSplit).join('/');
                            _context2.next = 8;
                            return (0, (_consumer2 || _load_consumer2()).listScope)({ scopeName, namespacesUsingWildcards });

                          case 8:
                            listResult = _context2.sent;

                            if (listResult.length) {
                              _context2.next = 11;
                              break;
                            }

                            throw new (_generalError || _load_generalError()).default(`no components found on the remote scope matching the "${idStr}" pattern`);

                          case 11:
                            _ids = listResult.map(function (result) {
                              return result.id;
                            });

                            bitIds.push.apply(bitIds, _toConsumableArray(_ids));
                            _context2.next = 16;
                            break;

                          case 15:
                            bitIds.push((_bitId || _load_bitId()).BitId.parse(idStr, true)); // we don't support importing without a scope name

                          case 16:
                          case 'end':
                            return _context2.stop();
                        }
                      }
                    }, _callee2, _this);
                  }));

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

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

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

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

      return _getBitIds;
    }()
  }, {
    key: 'importAccordingToBitMap',
    value: function () {
      var _ref4 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee4() {
        var authoredExportedComponents, importedComponents, componentsIdsToImport, compiler, tester, beforeImportVersions, componentsAndDependencies, importDetails, context, envsArgs, _envComponents, _compiler, _tester;

        return (_regenerator || _load_regenerator()).default.wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                this.options.objectsOnly = !this.options.merge && !this.options.override;

                authoredExportedComponents = this.consumer.bitMap.getAuthoredExportedComponents();
                importedComponents = this.consumer.bitMap.getAllBitIds([(_constants || _load_constants()).COMPONENT_ORIGINS.IMPORTED]);
                componentsIdsToImport = [].concat(_toConsumableArray(authoredExportedComponents), _toConsumableArray(importedComponents));
                compiler = void 0;
                tester = void 0;

                if (!(_ramda || _load_ramda()).default.isEmpty(componentsIdsToImport)) {
                  _context4.next = 17;
                  break;
                }

                if (this.options.withEnvironments) {
                  _context4.next = 9;
                  break;
                }

                throw new (_exceptions || _load_exceptions()).NothingToImport();

              case 9:
                _context4.next = 11;
                return this.consumer.compiler;

              case 11:
                compiler = _context4.sent;
                _context4.next = 14;
                return this.consumer.tester;

              case 14:
                tester = _context4.sent;

                if (!(!tester && !compiler)) {
                  _context4.next = 17;
                  break;
                }

                throw new (_exceptions || _load_exceptions()).NothingToImport();

              case 17:
                _context4.next = 19;
                return this._throwForModifiedOrNewComponents(componentsIdsToImport);

              case 19:
                _context4.next = 21;
                return this._getCurrentVersions(componentsIdsToImport);

              case 21:
                beforeImportVersions = _context4.sent;
                componentsAndDependencies = [];

                if (!componentsIdsToImport.length) {
                  _context4.next = 29;
                  break;
                }

                _context4.next = 26;
                return this.consumer.importComponents(componentsIdsToImport, true);

              case 26:
                componentsAndDependencies = _context4.sent;
                _context4.next = 29;
                return this._writeToFileSystem(componentsAndDependencies);

              case 29:
                _context4.next = 31;
                return this._getImportDetails(beforeImportVersions, componentsAndDependencies);

              case 31:
                importDetails = _context4.sent;

                if (!this.options.withEnvironments) {
                  _context4.next = 61;
                  break;
                }

                _context4.t0 = compiler;

                if (_context4.t0) {
                  _context4.next = 38;
                  break;
                }

                _context4.next = 37;
                return this.consumer.compiler;

              case 37:
                _context4.t0 = _context4.sent;

              case 38:
                compiler = _context4.t0;
                _context4.t1 = tester;

                if (_context4.t1) {
                  _context4.next = 44;
                  break;
                }

                _context4.next = 43;
                return this.consumer.tester;

              case 43:
                _context4.t1 = _context4.sent;

              case 44:
                tester = _context4.t1;
                context = { workspaceDir: this.consumer.getPath() };
                envsArgs = [this.consumer.scope, { verbose: this.options.verbose }, context];
                _envComponents = [];

                if (!compiler) {
                  _context4.next = 54;
                  break;
                }

                _context4.t2 = _envComponents;
                _context4.next = 52;
                return (_compiler = compiler).install.apply(_compiler, envsArgs);

              case 52:
                _context4.t3 = _context4.sent;

                _context4.t2.push.call(_context4.t2, _context4.t3);

              case 54:
                if (!tester) {
                  _context4.next = 60;
                  break;
                }

                _context4.t4 = _envComponents;
                _context4.next = 58;
                return (_tester = tester).install.apply(_tester, envsArgs);

              case 58:
                _context4.t5 = _context4.sent;

                _context4.t4.push.call(_context4.t4, _context4.t5);

              case 60:
                return _context4.abrupt('return', {
                  dependencies: componentsAndDependencies,
                  envComponents: (_ramda || _load_ramda()).default.flatten(_envComponents),
                  importDetails
                });

              case 61:
                return _context4.abrupt('return', { dependencies: componentsAndDependencies, importDetails });

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

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

      return importAccordingToBitMap;
    }()
  }, {
    key: '_getCurrentVersions',
    value: function () {
      var _ref5 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee6(ids) {
        var _this2 = this;

        var versionsP, versions;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                versionsP = ids.map(function () {
                  var _ref6 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee5(id) {
                    var modelComponent, idStr;
                    return (_regenerator || _load_regenerator()).default.wrap(function _callee5$(_context5) {
                      while (1) {
                        switch (_context5.prev = _context5.next) {
                          case 0:
                            _context5.next = 2;
                            return _this2.consumer.scope.getModelComponentIfExist(id);

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

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

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

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

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

                  return function (_x3) {
                    return _ref6.apply(this, arguments);
                  };
                }());
                _context6.next = 3;
                return Promise.all(versionsP);

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

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

      function _getCurrentVersions(_x2) {
        return _ref5.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 _ref7 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee8(currentVersions, components) {
        var _this3 = this;

        var detailsP;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee8$(_context8) {
          while (1) {
            switch (_context8.prev = _context8.next) {
              case 0:
                detailsP = components.map(function () {
                  var _ref8 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee7(component) {
                    var id, idStr, beforeImportVersions, modelComponent, afterImportVersions, versionDifference, getStatus, filesStatus;
                    return (_regenerator || _load_regenerator()).default.wrap(function _callee7$(_context7) {
                      while (1) {
                        switch (_context7.prev = _context7.next) {
                          case 0:
                            id = component.component.id;
                            idStr = id.toStringWithoutVersion();
                            beforeImportVersions = currentVersions[idStr];

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

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

                          case 5:
                            _context7.next = 7;
                            return _this3.consumer.scope.getModelComponentIfExist(id);

                          case 7:
                            modelComponent = _context7.sent;

                            if (modelComponent) {
                              _context7.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 = _this3.mergeStatus && _this3.mergeStatus[idStr] ? _this3.mergeStatus[idStr] : null;
                            return _context7.abrupt('return', { id: idStr, versions: versionDifference, status: getStatus(), filesStatus });

                          case 15:
                          case 'end':
                            return _context7.stop();
                        }
                      }
                    }, _callee7, _this3);
                  }));

                  return function (_x6) {
                    return _ref8.apply(this, arguments);
                  };
                }());
                return _context8.abrupt('return', Promise.all(detailsP));

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

      function _getImportDetails(_x4, _x5) {
        return _ref7.apply(this, arguments);
      }

      return _getImportDetails;
    }()
  }, {
    key: '_throwForPotentialIssues',
    value: function () {
      var _ref9 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee9(ids) {
        return (_regenerator || _load_regenerator()).default.wrap(function _callee9$(_context9) {
          while (1) {
            switch (_context9.prev = _context9.next) {
              case 0:
                _context9.next = 2;
                return this._throwForModifiedOrNewComponents(ids);

              case 2:
                this._throwForDifferentComponentWithSameName(ids);

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

      function _throwForPotentialIssues(_x7) {
        return _ref9.apply(this, arguments);
      }

      return _throwForPotentialIssues;
    }()
  }, {
    key: '_throwForModifiedOrNewComponents',
    value: function () {
      var _ref10 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee10(ids) {
        var _this4 = this;

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

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

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

              case 4:
                modifiedComponents = _context10.sent;

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

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

      function _throwForModifiedOrNewComponents(_x8) {
        return _ref10.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 _this5 = this;

      ids.forEach(function (id) {
        var existingId = _this5.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 _ref11 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee11(componentWithDependencies) {
        var component, componentStatus, mergeStatus, componentModel, existingBitMapBitId, fsComponent, currentlyUsedVersion, baseComponent, currentComponent, mergeResults;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee11$(_context11) {
          while (1) {
            switch (_context11.prev = _context11.next) {
              case 0:
                component = componentWithDependencies.component;
                _context11.next = 3;
                return this.consumer.getComponentStatusById(component.id);

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

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

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

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

              case 9:
                componentModel = _context11.sent;

                if (componentModel) {
                  _context11.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 });
                _context11.next = 15;
                return this.consumer.loadComponent(existingBitMapBitId);

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

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

              case 22:
                currentComponent = _context11.sent;
                _context11.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 = _context11.sent;

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

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

      function _getMergeStatus(_x9) {
        return _ref11.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 _updateComponentFilesPerMergeStrategy(componentMergeStatus) {
      var mergeResults = componentMergeStatus.mergeResults;
      if (!mergeResults) return null;
      var component = componentMergeStatus.componentWithDependencies.component;
      var files = component.files;

      var filesStatus = {};
      if (mergeResults.hasConflicts && this.options.mergeStrategy === (_mergeVersion || _load_mergeVersion()).MergeOptions.ours) {
        // 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 filesStatus;
      }
      if (mergeResults.hasConflicts && this.options.mergeStrategy === (_mergeVersion || _load_mergeVersion()).MergeOptions.theirs) {
        // 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 filesStatus;
      }
      return (0, (_checkoutVersion || _load_checkoutVersion()).applyModifiedVersion)(component.files, mergeResults, this.options.mergeStrategy);
    }

    /**
     * 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 _ref12 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee12(componentsWithDependencies) {
        var _this6 = this;

        var componentsStatusP, componentsStatus, componentWithConflict, 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 _this6._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 = {};

                componentsToWrite = componentsStatus.map(function (componentStatus) {
                  var filesStatus = _this6._updateComponentFilesPerMergeStrategy(componentStatus);
                  var componentWithDependencies = componentStatus.componentWithDependencies;
                  if (!filesStatus) return componentWithDependencies;
                  _this6.mergeStatus[componentWithDependencies.component.id.toStringWithoutVersion()] = filesStatus;
                  var unchangedFiles = Object.keys(filesStatus).filter(function (file) {
                    return filesStatus[file] === (_mergeVersion || _load_mergeVersion()).FileStatus.unchanged;
                  });
                  if (unchangedFiles.length === Object.keys(filesStatus).length) {
                    // all files are unchanged
                    return null;
                  }
                  return componentWithDependencies;
                });
                removeNulls = (_ramda || _load_ramda()).default.reject((_ramda || _load_ramda()).default.isNil);
                return _context12.abrupt('return', removeNulls(componentsToWrite));

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

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

      return updateAllComponentsAccordingToMergeStrategy;
    }()
  }, {
    key: '_writeToFileSystem',
    value: function () {
      var _ref13 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__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,
                  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(_x11) {
        return _ref13.apply(this, arguments);
      }

      return _writeToFileSystem;
    }()
  }]);

  return ImportComponents;
}();

exports.default = ImportComponents;