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

function _load_chalk() {
  return _chalk = _interopRequireDefault(require('chalk'));
}

var _path;

function _load_path() {
  return _path = _interopRequireDefault(require('path'));
}

var _ramda;

function _load_ramda() {
  return _ramda = _interopRequireDefault(require('ramda'));
}

var _command;

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

var _consumer;

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

var _addTestsWithoutId;

function _load_addTestsWithoutId() {
  return _addTestsWithoutId = _interopRequireDefault(require('../exceptions/add-tests-without-id'));
}

var _constants;

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

var _generalError;

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

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 Add = function (_Command) {
  _inherits(Add, _Command);

  function Add() {
    var _ref;

    var _temp, _this, _ret;

    _classCallCheck(this, Add);

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

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Add.__proto__ || Object.getPrototypeOf(Add)).call.apply(_ref, [this].concat(args))), _this), _this.name = 'add [path...]', _this.description = `add any subset of files to be tracked as a component(s)\n  https://${(_constants || _load_constants()).BASE_DOCS_DOMAIN}/docs/isolating-and-tracking-components.html`, _this.alias = 'a', _this.opts = [['i', 'id <name>', 'component id, if not specified the name will be '], ['m', 'main <file>', 'implementation/index file name or dsl (src/{PARENT}/{FILE_NAME})'], ['t', 'tests <file...>', 'spec/test file name or dsl (tests/{PARENT}/{FILE_NAME})'], ['n', 'namespace <namespace>', 'component namespace'], ['e', 'exclude <file...>', 'exclude file name or dsl (src/{PARENT}/{FILE_NAME})'], ['o', 'override <boolean>', 'override existing component if exists (default = false)']], _this.loader = true, _this.migration = true, _temp), _possibleConstructorReturn(_this, _ret);
  }

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

      var id = _ref3.id,
          main = _ref3.main,
          tests = _ref3.tests,
          namespace = _ref3.namespace,
          exclude = _ref3.exclude,
          _ref3$override = _ref3.override,
          override = _ref3$override === undefined ? false : _ref3$override;

      if (namespace && id) {
        throw new (_generalError || _load_generalError()).default('please use either [id] or [namespace] to add a particular component');
      }

      var normalizedPaths = paths.map(function (p) {
        return (_path || _load_path()).default.normalize(p);
      });
      var testsArray = tests ? this.splitList(tests).map(function (filePath) {
        return (_path || _load_path()).default.normalize(filePath.trim());
      }) : [];
      var excludedFiles = exclude ? this.splitList(exclude).map(function (filePath) {
        return (_path || _load_path()).default.normalize(filePath.trim());
      }) : [];

      // check if user is trying to add test files only without id
      if (!(_ramda || _load_ramda()).default.isEmpty(tests) && !id && (_ramda || _load_ramda()).default.isEmpty(normalizedPaths)) {
        throw new (_addTestsWithoutId || _load_addTestsWithoutId()).default();
      }

      return (0, (_consumer || _load_consumer()).add)({
        componentPaths: normalizedPaths,
        id,
        main: main ? (_path || _load_path()).default.normalize(main) : undefined,
        namespace,
        tests: testsArray,
        exclude: excludedFiles,
        override
      });
    }
  }, {
    key: 'report',
    value: function report(_ref5) {
      var addedComponents = _ref5.addedComponents,
          warnings = _ref5.warnings;

      var paintWarning = function paintWarning() {
        if (warnings) {
          var warn = Object.keys(warnings).map(function (key) {
            return (_chalk || _load_chalk()).default.yellow(`warning: files ${(_chalk || _load_chalk()).default.bold(warnings[key].join(', '))} already used by component: ${key}`);
          }).filter(function (x) {
            return x;
          }).join('\n');
          if (!(_ramda || _load_ramda()).default.isEmpty(warn)) return `${warn}\n`;
        }
        return '';
      };

      if (addedComponents.length > 1) {
        return paintWarning() + (_chalk || _load_chalk()).default.green(`tracking ${addedComponents.length} new components`);
      }

      return paintWarning() + (_ramda || _load_ramda()).default.flatten(addedComponents.map(function (result) {
        if (result.files.length === 0) {
          return (_chalk || _load_chalk()).default.underline.red(`could not track component ${(_chalk || _load_chalk()).default.bold(result.id)}: no files to track`);
        }
        var title = (_chalk || _load_chalk()).default.underline(`tracking component ${(_chalk || _load_chalk()).default.bold(result.id)}:\n`);
        var files = result.files.map(function (file) {
          return (_chalk || _load_chalk()).default.green(`added ${file.relativePath}`);
        });
        return title + files.join('\n');
      })).join('\n\n');
    }
  }]);

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

exports.default = Add;