"use strict";

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

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

function _defineProperty2() {
  const data = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

  _defineProperty2 = 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 _command() {
  const data = _interopRequireDefault(require("../../command"));

  _command = function () {
    return data;
  };

  return data;
}

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

  _consumer = function () {
    return data;
  };

  return data;
}

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

  _utils = function () {
    return data;
  };

  return data;
}

function _chalkBox() {
  const data = require("../../chalk-box");

  _chalkBox = function () {
    return data;
  };

  return data;
}

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

  _component = function () {
    return data;
  };

  return data;
}

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

  _scope = function () {
    return data;
  };

  return data;
}

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

  _generalError = function () {
    return data;
  };

  return data;
}

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

  _constants = function () {
    return data;
  };

  return data;
}

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

  _mergeVersion = function () {
    return data;
  };

  return data;
}

class Import extends _command().default {
  constructor(...args) {
    super(...args);
    (0, _defineProperty2().default)(this, "name", 'import [ids...]');
    (0, _defineProperty2().default)(this, "description", `import components into your current workspace.\n  https://${_constants().BASE_DOCS_DOMAIN}/docs/importing-components.html`);
    (0, _defineProperty2().default)(this, "alias", 'i');
    (0, _defineProperty2().default)(this, "opts", [['t', 'tester', 'import a tester environment component'], ['c', 'compiler', 'import a compiler environment component'], ['x', 'extension', 'import an extension component'], ['e', 'environment', 'install development environment dependencies (compiler and tester)'], ['p', 'path <path>', 'import components into a specific directory'], ['o', 'objects', "import components objects only, don't write the components to the file system. This is a default behavior for import with no id"], ['d', 'display-dependencies', 'display the imported dependencies'], ['O', 'override', 'override local changes'], ['v', 'verbose', 'showing verbose output for inspection'], ['', 'ignore-dist', "skip writing the component's build files during import"], ['', 'conf [path]', 'write the configuration file (bit.json) and the envs configuration files (use --conf without path to write to the default dir)'], ['', 'skip-npm-install', 'do not install packages of the imported components. (it automatically enables save-dependencies-as-components flag)'], ['', 'ignore-package-json', 'do not generate package.json for the imported component(s). (it automatically enables skip-npm-install and save-dependencies-as-components flags)'], ['m', 'merge [strategy]', 'merge local changes with the imported version. strategy should be "theirs", "ours" or "manual"']]);
    (0, _defineProperty2().default)(this, "loader", true);
    (0, _defineProperty2().default)(this, "migration", true);
  }

  action([ids], {
    tester = false,
    compiler = false,
    extension = false,
    path,
    objects = false,
    displayDependencies = false,
    environment = false,
    override = false,
    verbose = false,
    ignoreDist = false,
    conf,
    skipNpmInstall = false,
    ignorePackageJson = false,
    merge
  }, packageManagerArgs) {
    if (tester && compiler) {
      throw new (_generalError().default)('you cant use tester and compiler flags combined');
    }

    if (objects && merge) {
      throw new (_generalError().default)('you cant use --objects and --merge flags combined');
    }

    if (override && merge) {
      throw new (_generalError().default)('you cant use --override and --merge flags combined');
    }

    let mergeStrategy;

    if (merge && _ramda().default.is(String, merge)) {
      const options = Object.keys(_mergeVersion().MergeOptions);

      if (!options.includes(merge)) {
        throw new (_generalError().default)(`merge must be one of the following: ${options.join(', ')}`);
      }

      mergeStrategy = merge;
    }

    const environmentOptions = {
      tester,
      compiler,
      extension
    };
    const importOptions = {
      ids,
      verbose,
      merge: !!merge,
      mergeStrategy,
      writeToPath: path,
      objectsOnly: objects,
      withEnvironments: environment,
      override,
      writeDists: !ignoreDist,
      writeConfig: !!conf,
      installNpmPackages: !skipNpmInstall,
      writePackageJson: !ignorePackageJson
    }; // From the CLI you can pass the conf as path or just --conf (which will later translate to the default eject conf folder)

    if (typeof conf === 'string') {
      importOptions.configDir = conf;
    }

    return (0, _consumer().importAction)(environmentOptions, importOptions, packageManagerArgs).then(importResults => _ramda().default.assoc('displayDependencies', displayDependencies, importResults));
  }

  report({
    dependencies,
    envComponents,
    importDetails,
    warnings,
    displayDependencies
  }) {
    let dependenciesOutput;
    let envComponentsOutput;

    if (dependencies && !_ramda().default.isEmpty(dependencies)) {
      const components = dependencies.map(_ramda().default.prop('component'));

      const peerDependencies = _ramda().default.flatten(dependencies.map(_ramda().default.prop('dependencies')), dependencies.map(_ramda().default.prop('devDependencies')));

      const title = components.length === 1 ? 'successfully imported one component' : `successfully imported ${components.length} components`;
      const componentDependencies = components.map(component => {
        const details = importDetails.find(c => c.id === component.id.toStringWithoutVersion());
        if (!details) throw new Error(`missing details of component ${component.id.toString()}`);
        return (0, _chalkBox().formatPlainComponentItemWithVersions)(component, details);
      });
      const componentDependenciesOutput = [_chalk().default.green(title)].concat(componentDependencies).join('\n');
      const peerDependenciesOutput = peerDependencies && !_ramda().default.isEmpty(peerDependencies) && displayDependencies ? (0, _utils().immutableUnshift)(_ramda().default.uniq(peerDependencies.map(_chalkBox().formatPlainComponentItem)), _chalk().default.green(`\n\nsuccessfully imported ${components.length} component dependencies`)).join('\n') : '';
      dependenciesOutput = componentDependenciesOutput + peerDependenciesOutput;
    }

    if (envComponents && !_ramda().default.isEmpty(envComponents)) {
      envComponentsOutput = (0, _utils().immutableUnshift)(envComponents.map(envDependency => (0, _chalkBox().formatPlainComponentItem)(envDependency.component)), _chalk().default.green('the following component environments were installed')).join('\n');
    }

    const getImportOutput = () => {
      if (dependenciesOutput && !envComponentsOutput) return dependenciesOutput;
      if (!dependenciesOutput && envComponentsOutput) return envComponentsOutput;

      if (dependenciesOutput && envComponentsOutput) {
        return `${dependenciesOutput}\n\n${envComponentsOutput}`;
      }

      return _chalk().default.yellow('nothing to import');
    };

    const logObject = obj => `> ${_ramda().default.keys(obj)[0]}: ${_ramda().default.values(obj)[0]}`;

    const getWarningOutput = () => {
      if (!warnings) return '';
      let output = '\n';

      if (!_ramda().default.isEmpty(warnings.notInBoth)) {
        output += _chalk().default.red.underline('\nerror - missing the following package dependencies. please install and add to package.json.\n');
        output += _chalk().default.red(`${warnings.notInBoth.map(logObject).join('\n')}\n`);
      }

      if (!_ramda().default.isEmpty(warnings.notInPackageJson)) {
        output += _chalk().default.yellow.underline('\nwarning - add the following packages to package.json\n');
        output += _chalk().default.yellow(`${warnings.notInPackageJson.map(logObject).join('\n')}\n`);
      }

      if (!_ramda().default.isEmpty(warnings.notInNodeModules)) {
        output += _chalk().default.yellow.underline('\nwarning - following packages are not installed. please install them.\n');
        output += _chalk().default.yellow(`${warnings.notInNodeModules.map(logObject).join('\n')}\n`);
      }

      return output === '\n' ? '' : output;
    };

    return getImportOutput() + getWarningOutput();
  }

}

exports.default = Import;