'use strict';

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

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

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 _command;

function _load_command() {
  return _command = _interopRequireDefault(require('../../command'));
}

var _consumer;

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

var _utils;

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

var _chalkBox;

function _load_chalkBox() {
  return _chalkBox = require('../../chalk-box');
}

var _component;

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

var _scope;

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

var _generalError;

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

var _constants;

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

var _mergeVersion;

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

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

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

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Import = function (_Command) {
  _inherits(Import, _Command);

  function Import() {
    var _ref;

    var _temp, _this, _ret;

    _classCallCheck(this, Import);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Import.__proto__ || Object.getPrototypeOf(Import)).call.apply(_ref, [this].concat(args))), _this), _this.name = 'import [ids...]', _this.description = `import components into your current workspace.\n  https://${(_constants || _load_constants()).BASE_DOCS_DOMAIN}/docs/importing-components.html`, _this.alias = 'i', _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', 'write dist files (when exist) to the configured directory'], ['', 'conf', 'write the configuration file (bit.json)'], ['', '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"']], _this.loader = true, _this.migration = true, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(Import, [{
    key: 'action',
    value: function action(_ref2, _ref3, packageManagerArgs) {
      var _ref4 = _slicedToArray(_ref2, 1),
          ids = _ref4[0];

      var _ref3$tester = _ref3.tester,
          tester = _ref3$tester === undefined ? false : _ref3$tester,
          _ref3$compiler = _ref3.compiler,
          compiler = _ref3$compiler === undefined ? false : _ref3$compiler,
          _ref3$extension = _ref3.extension,
          extension = _ref3$extension === undefined ? false : _ref3$extension,
          path = _ref3.path,
          _ref3$objects = _ref3.objects,
          objects = _ref3$objects === undefined ? false : _ref3$objects,
          _ref3$displayDependen = _ref3.displayDependencies,
          displayDependencies = _ref3$displayDependen === undefined ? false : _ref3$displayDependen,
          _ref3$environment = _ref3.environment,
          environment = _ref3$environment === undefined ? false : _ref3$environment,
          _ref3$override = _ref3.override,
          override = _ref3$override === undefined ? false : _ref3$override,
          _ref3$verbose = _ref3.verbose,
          verbose = _ref3$verbose === undefined ? false : _ref3$verbose,
          _ref3$ignoreDist = _ref3.ignoreDist,
          ignoreDist = _ref3$ignoreDist === undefined ? false : _ref3$ignoreDist,
          _ref3$conf = _ref3.conf,
          conf = _ref3$conf === undefined ? false : _ref3$conf,
          _ref3$skipNpmInstall = _ref3.skipNpmInstall,
          skipNpmInstall = _ref3$skipNpmInstall === undefined ? false : _ref3$skipNpmInstall,
          _ref3$ignorePackageJs = _ref3.ignorePackageJson,
          ignorePackageJson = _ref3$ignorePackageJs === undefined ? false : _ref3$ignorePackageJs,
          merge = _ref3.merge;

      if (tester && compiler) {
        throw new (_generalError || _load_generalError()).default('you cant use tester and compiler flags combined');
      }
      if (objects && merge) {
        throw new (_generalError || _load_generalError()).default('you cant use --objects and --merge flags combined');
      }
      if (override && merge) {
        throw new (_generalError || _load_generalError()).default('you cant use --override and --merge flags combined');
      }
      var mergeStrategy = void 0;
      if (merge && (_ramda || _load_ramda()).default.is(String, merge)) {
        var options = Object.keys((_mergeVersion || _load_mergeVersion()).MergeOptions);
        if (!options.includes(merge)) {
          throw new (_generalError || _load_generalError()).default(`merge must be one of the following: ${options.join(', ')}`);
        }
        mergeStrategy = merge;
      }
      var environmentOptions = {
        tester,
        compiler,
        extension
      };

      var importOptions = {
        ids,
        verbose,
        merge: !!merge,
        mergeStrategy,
        writeToPath: path,
        objectsOnly: objects,
        withEnvironments: environment,
        override,
        writeDists: !ignoreDist,
        writeBitJson: conf,
        installNpmPackages: !skipNpmInstall,
        writePackageJson: !ignorePackageJson
      };
      return (0, (_consumer || _load_consumer()).importAction)(environmentOptions, importOptions, packageManagerArgs).then(function (importResults) {
        return (_ramda || _load_ramda()).default.assoc('displayDependencies', displayDependencies, importResults);
      });
    }
  }, {
    key: 'report',
    value: function report(_ref5) {
      var dependencies = _ref5.dependencies,
          envDependencies = _ref5.envDependencies,
          importDetails = _ref5.importDetails,
          warnings = _ref5.warnings,
          displayDependencies = _ref5.displayDependencies;

      var dependenciesOutput = void 0;
      var envDependenciesOutput = void 0;

      if (dependencies && !(_ramda || _load_ramda()).default.isEmpty(dependencies)) {
        var components = dependencies.map((_ramda || _load_ramda()).default.prop('component'));
        var peerDependencies = (_ramda || _load_ramda()).default.flatten(dependencies.map((_ramda || _load_ramda()).default.prop('dependencies')), dependencies.map((_ramda || _load_ramda()).default.prop('devDependencies')));

        var title = components.length === 1 ? 'successfully imported one component' : `successfully imported ${components.length} components`;
        var componentDependencies = components.map(function (component) {
          var details = importDetails.find(function (c) {
            return c.id === component.id.toStringWithoutVersion();
          });
          if (!details) throw new Error(`missing details of component ${component.id.toString()}`);
          return (0, (_chalkBox || _load_chalkBox()).formatPlainComponentItemWithVersions)(component, details);
        });
        var componentDependenciesOutput = [(_chalk || _load_chalk()).default.green(title)].concat(componentDependencies).join('\n');

        var peerDependenciesOutput = peerDependencies && !(_ramda || _load_ramda()).default.isEmpty(peerDependencies) && displayDependencies ? (0, (_utils || _load_utils()).immutableUnshift)((_ramda || _load_ramda()).default.uniq(peerDependencies.map((_chalkBox || _load_chalkBox()).formatPlainComponentItem)), (_chalk || _load_chalk()).default.green(`\n\nsuccessfully imported ${components.length} component dependencies`)).join('\n') : '';

        dependenciesOutput = componentDependenciesOutput + peerDependenciesOutput;
      }

      if (envDependencies && !(_ramda || _load_ramda()).default.isEmpty(envDependencies)) {
        envDependenciesOutput = (0, (_utils || _load_utils()).immutableUnshift)(envDependencies.map(function (envDependency) {
          return (0, (_chalkBox || _load_chalkBox()).formatPlainComponentItem)(envDependency.component);
        }), (_chalk || _load_chalk()).default.green('the following component environments were installed')).join('\n');
      }

      var getImportOutput = function getImportOutput() {
        if (dependenciesOutput && !envDependenciesOutput) return dependenciesOutput;
        if (!dependenciesOutput && envDependenciesOutput) return envDependenciesOutput;
        if (dependenciesOutput && envDependenciesOutput) {
          return `${dependenciesOutput}\n\n${envDependenciesOutput}`;
        }

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

      var logObject = function logObject(obj) {
        return `> ${(_ramda || _load_ramda()).default.keys(obj)[0]}: ${(_ramda || _load_ramda()).default.values(obj)[0]}`;
      };
      var getWarningOutput = function getWarningOutput() {
        if (!warnings) return '';
        var output = '\n';

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

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

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

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

      return getImportOutput() + getWarningOutput();
    }
  }]);

  return Import;
}((_command || _load_command()).default);

exports.default = Import;