"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

function _bluebird() {
  const data = require("bluebird");

  _bluebird = function () {
    return data;
  };

  return data;
}

function _ramda() {
  const data = _interopRequireDefault(require("ramda"));

  _ramda = function () {
    return data;
  };

  return data;
}

function _chalk() {
  const data = _interopRequireDefault(require("chalk"));

  _chalk = function () {
    return data;
  };

  return data;
}

function _exceptions() {
  const data = require("../exceptions");

  _exceptions = function () {
    return data;
  };

  return data;
}

function _bitId() {
  const data = require("../../bit-id");

  _bitId = function () {
    return data;
  };

  return data;
}

function _component() {
  const data = _interopRequireDefault(require("../component"));

  _component = function () {
    return data;
  };

  return data;
}

function _consumer() {
  const data = require("../../consumer");

  _consumer = function () {
    return data;
  };

  return data;
}

function _scope() {
  const data = require("../../scope");

  _scope = function () {
    return data;
  };

  return data;
}

function _loader() {
  const data = _interopRequireDefault(require("../../cli/loader"));

  _loader = function () {
    return data;
  };

  return data;
}

function _loaderMessages() {
  const data = require("../../cli/loader/loader-messages");

  _loaderMessages = function () {
    return data;
  };

  return data;
}

function _logger() {
  const data = _interopRequireDefault(require("../../logger/logger"));

  _logger = function () {
    return data;
  };

  return data;
}

function _utils() {
  const data = require("../../utils");

  _utils = function () {
    return data;
  };

  return data;
}

function _generalError() {
  const data = _interopRequireDefault(require("../../error/general-error"));

  _generalError = function () {
    return data;
  };

  return data;
}

function _checkoutVersion() {
  const data = require("../versions-ops/checkout-version");

  _checkoutVersion = function () {
    return data;
  };

  return data;
}

function _mergeVersion() {
  const data = require("../versions-ops/merge-version");

  _mergeVersion = function () {
    return data;
  };

  return data;
}

function _manyComponentsWriter() {
  const data = _interopRequireDefault(require("./many-components-writer"));

  _manyComponentsWriter = function () {
    return data;
  };

  return data;
}

function _constants() {
  const data = require("../../constants");

  _constants = function () {
    return data;
  };

  return data;
}

function _hasWildcard() {
  const data = _interopRequireDefault(require("../../utils/string/has-wildcard"));

  _hasWildcard = function () {
    return data;
  };

  return data;
}

function _consumer2() {
  const data = require("../../api/consumer");

  _consumer2 = function () {
    return data;
  };

  return data;
}

class ImportComponents {
  constructor(consumer, options) {
    this.consumer = consumer;
    this.scope = consumer.scope;
    this.options = options;
  }

  importComponents() {
    _loader().default.start(_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().default.isEmpty(this.options.ids)) {
      return this.importAccordingToBitMap();
    }

    return this.importSpecificComponents();
  }

  importSpecificComponents() {
    var _this = this;

    return (0, _bluebird().coroutine)(function* () {
      _logger().default.debug(`importSpecificComponents, Ids: ${_this.options.ids.join(', ')}`);

      const bitIds = yield _this._getBitIds();
      const beforeImportVersions = yield _this._getCurrentVersions(bitIds);
      yield _this._throwForPotentialIssues(bitIds);
      const componentsWithDependencies = yield _this.consumer.importComponents(bitIds, true, _this.options.saveDependenciesAsComponents);
      yield _this._writeToFileSystem(componentsWithDependencies);
      const importDetails = yield _this._getImportDetails(beforeImportVersions, componentsWithDependencies);
      return {
        dependencies: componentsWithDependencies,
        importDetails
      };
    })();
  }

  _getBitIds() {
    var _this2 = this;

    return (0, _bluebird().coroutine)(function* () {
      const bitIds = [];
      yield Promise.all(_this2.options.ids.map(
      /*#__PURE__*/
      function () {
        var _ref = (0, _bluebird().coroutine)(function* (idStr) {
          if ((0, _hasWildcard().default)(idStr)) {
            if (!idStr.includes('/')) {
              throw new (_generalError().default)(`import with wildcards expects full scope-name before the wildcards, instead, got "${idStr}"`);
            }

            const idSplit = idStr.split('/');
            const scopeName = idSplit[0];

            const namespacesUsingWildcards = _ramda().default.tail(idSplit).join('/');

            const listResult = yield (0, _consumer2().listScope)({
              scopeName,
              namespacesUsingWildcards
            });

            if (!listResult.length) {
              throw new (_generalError().default)(`no components found on the remote scope matching the "${idStr}" pattern`);
            }

            _loader().default.start(_loaderMessages().BEFORE_IMPORT_ACTION); // it stops the previous loader of BEFORE_REMOTE_LIST


            const ids = listResult.map(result => result.id);
            bitIds.push(...ids);
          } else {
            bitIds.push(_bitId().BitId.parse(idStr, true)); // we don't support importing without a scope name
          }
        });

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

  importAccordingToBitMap() {
    var _this3 = this;

    return (0, _bluebird().coroutine)(function* () {
      _this3.options.objectsOnly = !_this3.options.merge && !_this3.options.override;

      const authoredExportedComponents = _this3.consumer.bitMap.getAuthoredExportedComponents();

      const importedComponents = _this3.consumer.bitMap.getAllBitIds([_constants().COMPONENT_ORIGINS.IMPORTED]);

      const componentsIdsToImport = [...authoredExportedComponents, ...importedComponents];
      let compiler;
      let tester;

      if (_ramda().default.isEmpty(componentsIdsToImport)) {
        if (!_this3.options.withEnvironments) {
          throw new (_exceptions().NothingToImport)();
        }

        compiler = yield _this3.consumer.compiler;
        tester = yield _this3.consumer.tester;

        if (!tester && !compiler) {
          throw new (_exceptions().NothingToImport)();
        }
      }

      yield _this3._throwForModifiedOrNewComponents(componentsIdsToImport);
      const beforeImportVersions = yield _this3._getCurrentVersions(componentsIdsToImport);
      let componentsAndDependencies = [];

      if (componentsIdsToImport.length) {
        componentsAndDependencies = yield _this3.consumer.importComponents(componentsIdsToImport, true);
        yield _this3._writeToFileSystem(componentsAndDependencies);
      }

      const importDetails = yield _this3._getImportDetails(beforeImportVersions, componentsAndDependencies);

      if (_this3.options.withEnvironments) {
        compiler = compiler || (yield _this3.consumer.compiler);
        tester = tester || (yield _this3.consumer.tester);
        const context = {
          workspaceDir: _this3.consumer.getPath()
        };
        const envsArgs = [_this3.consumer.scope, {
          verbose: _this3.options.verbose
        }, context];
        const envComponents = [];

        if (compiler) {
          envComponents.push((yield compiler.install(...envsArgs)));
        }

        if (tester) {
          envComponents.push((yield tester.install(...envsArgs)));
        }

        return {
          dependencies: componentsAndDependencies,
          envComponents: _ramda().default.flatten(envComponents),
          importDetails
        };
      }

      return {
        dependencies: componentsAndDependencies,
        importDetails
      };
    })();
  }

  _getCurrentVersions(ids) {
    var _this4 = this;

    return (0, _bluebird().coroutine)(function* () {
      const versionsP = ids.map(
      /*#__PURE__*/
      function () {
        var _ref2 = (0, _bluebird().coroutine)(function* (id) {
          const modelComponent = yield _this4.consumer.scope.getModelComponentIfExist(id);
          const idStr = id.toStringWithoutVersion();
          if (!modelComponent) return [idStr, []];
          return [idStr, modelComponent.listVersions()];
        });

        return function (_x2) {
          return _ref2.apply(this, arguments);
        };
      }());
      const versions = yield Promise.all(versionsP);
      return _ramda().default.fromPairs(versions);
    })();
  }
  /**
   * get import details, includes the diff between the versions array before import and after import
   */


  _getImportDetails(currentVersions, components) {
    var _this5 = this;

    return (0, _bluebird().coroutine)(function* () {
      const detailsP = components.map(
      /*#__PURE__*/
      function () {
        var _ref3 = (0, _bluebird().coroutine)(function* (component) {
          const id = component.component.id;
          const idStr = id.toStringWithoutVersion();
          const beforeImportVersions = currentVersions[idStr];

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

          const modelComponent = yield _this5.consumer.scope.getModelComponentIfExist(id);
          if (!modelComponent) throw new (_generalError().default)(`imported component ${idStr} was not found in the model`);
          const afterImportVersions = modelComponent.listVersions();

          const versionDifference = _ramda().default.difference(afterImportVersions, beforeImportVersions);

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

          const filesStatus = _this5.mergeStatus && _this5.mergeStatus[idStr] ? _this5.mergeStatus[idStr] : null;
          return {
            id: idStr,
            versions: versionDifference,
            status: getStatus(),
            filesStatus
          };
        });

        return function (_x3) {
          return _ref3.apply(this, arguments);
        };
      }());
      return Promise.all(detailsP);
    })();
  }

  _throwForPotentialIssues(ids) {
    var _this6 = this;

    return (0, _bluebird().coroutine)(function* () {
      yield _this6._throwForModifiedOrNewComponents(ids);

      _this6._throwForDifferentComponentWithSameName(ids);
    })();
  }

  _throwForModifiedOrNewComponents(ids) {
    var _this7 = this;

    return (0, _bluebird().coroutine)(function* () {
      // the typical objectsOnly option is when a user cloned a project with components tagged to the source code, but
      // doesn't have the model objects. in that case, calling getComponentStatusById() may return an error as it relies
      // on the model objects when there are dependencies
      if (_this7.options.override || _this7.options.objectsOnly || _this7.options.merge) return Promise.resolve();
      const modifiedComponents = yield (0, _utils().filterAsync)(ids, id => {
        return _this7.consumer.getComponentStatusById(id).then(status => status.modified || status.newlyCreated);
      });

      if (modifiedComponents.length) {
        throw new (_generalError().default)(_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')} `));
      }

      return Promise.resolve();
    })();
  }
  /**
   * 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.
   */


  _throwForDifferentComponentWithSameName(ids) {
    ids.forEach(id => {
      const existingId = this.consumer.getParsedIdIfExist(id.toStringWithoutVersion());

      if (existingId && !existingId.hasScope()) {
        throw new (_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`);
      }
    });
  }

  _getMergeStatus(componentWithDependencies) {
    var _this8 = this;

    return (0, _bluebird().coroutine)(function* () {
      const component = componentWithDependencies.component;
      const componentStatus = yield _this8.consumer.getComponentStatusById(component.id);
      const mergeStatus = {
        componentWithDependencies,
        mergeResults: null
      };
      if (!componentStatus.modified) return mergeStatus;
      const componentModel = yield _this8.consumer.scope.sources.get(component.id);

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

      const existingBitMapBitId = _this8.consumer.bitMap.getBitId(component.id, {
        ignoreVersion: true
      });

      const fsComponent = yield _this8.consumer.loadComponent(existingBitMapBitId);
      const currentlyUsedVersion = existingBitMapBitId.version;
      const baseComponent = yield _this8.consumer.loadComponentFromModel(existingBitMapBitId);
      const currentComponent = yield _this8.consumer.loadComponentFromModel(component.id);
      const mergeResults = yield (0, _mergeVersion().threeWayMerge)({
        consumer: _this8.consumer,
        otherComponent: fsComponent,
        otherVersion: currentlyUsedVersion,
        currentComponent,
        // $FlowFixMe
        currentVersion: component.id.version,
        baseComponent
      });
      mergeStatus.mergeResults = mergeResults;
      return mergeStatus;
    })();
  }
  /**
   * 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())
   */


  _updateComponentFilesPerMergeStrategy(componentMergeStatus) {
    const mergeResults = componentMergeStatus.mergeResults;
    if (!mergeResults) return null;
    const component = componentMergeStatus.componentWithDependencies.component;
    const files = component.files;
    const filesStatus = {};

    if (mergeResults.hasConflicts && this.options.mergeStrategy === _mergeVersion().MergeOptions.ours) {
      // don't write the files to the filesystem, only bump the bitmap version.
      files.forEach(file => {
        filesStatus[(0, _utils().pathNormalizeToLinux)(file.relative)] = _mergeVersion().FileStatus.unchanged;
      });
      this.consumer.bitMap.updateComponentId(component.id);
      this.consumer.bitMap.hasChanged = true;
      return filesStatus;
    }

    if (mergeResults.hasConflicts && this.options.mergeStrategy === _mergeVersion().MergeOptions.theirs) {
      // the local changes will be overridden (as if the user entered --override flag for this component)
      files.forEach(file => {
        filesStatus[(0, _utils().pathNormalizeToLinux)(file.relative)] = _mergeVersion().FileStatus.updated;
      });
      return filesStatus;
    }

    return (0, _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
   */


  updateAllComponentsAccordingToMergeStrategy(componentsWithDependencies) {
    var _this9 = this;

    return (0, _bluebird().coroutine)(function* () {
      if (!_this9.options.merge) return componentsWithDependencies;
      const componentsStatusP = componentsWithDependencies.map(componentWithDependencies => {
        return _this9._getMergeStatus(componentWithDependencies);
      });
      const componentsStatus = yield Promise.all(componentsStatusP);
      const componentWithConflict = componentsStatus.find(component => component.mergeResults && component.mergeResults.hasConflicts);

      if (componentWithConflict && !_this9.options.mergeStrategy) {
        _this9.options.mergeStrategy = yield (0, _mergeVersion().getMergeStrategyInteractive)();
      }

      _this9.mergeStatus = {};
      const componentsToWrite = componentsStatus.map(componentStatus => {
        const filesStatus = _this9._updateComponentFilesPerMergeStrategy(componentStatus);

        const componentWithDependencies = componentStatus.componentWithDependencies;
        if (!filesStatus) return componentWithDependencies;
        _this9.mergeStatus[componentWithDependencies.component.id.toStringWithoutVersion()] = filesStatus;
        const unchangedFiles = Object.keys(filesStatus).filter(file => filesStatus[file] === _mergeVersion().FileStatus.unchanged);

        if (unchangedFiles.length === Object.keys(filesStatus).length) {
          // all files are unchanged
          return null;
        }

        return componentWithDependencies;
      });

      const removeNulls = _ramda().default.reject(_ramda().default.isNil);

      return removeNulls(componentsToWrite);
    })();
  }

  _writeToFileSystem(componentsWithDependencies) {
    var _this10 = this;

    return (0, _bluebird().coroutine)(function* () {
      if (_this10.options.objectsOnly) return;
      const componentsToWrite = yield _this10.updateAllComponentsAccordingToMergeStrategy(componentsWithDependencies);

      if (_this10.options.writeConfig && !_this10.options.configDir) {
        _this10.options.configDir = _this10.consumer.dirStructure.ejectedEnvsDirStructure;
      }

      const manyComponentsWriter = new (_manyComponentsWriter().default)({
        consumer: _this10.consumer,
        componentsWithDependencies: componentsToWrite,
        writeToPath: _this10.options.writeToPath,
        writePackageJson: _this10.options.writePackageJson,
        writeConfig: _this10.options.writeConfig,
        configDir: _this10.options.configDir,
        writeDists: _this10.options.writeDists,
        installNpmPackages: _this10.options.installNpmPackages,
        verbose: _this10.options.verbose,
        override: _this10.options.override
      });
      yield manyComponentsWriter.writeAll();
    })();
  }

}

exports.default = ImportComponents;