'use strict';

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

var _regenerator;

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

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 _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _fsExtra;

function _load_fsExtra() {
  return _fsExtra = _interopRequireDefault(require('fs-extra'));
}

var _ramda;

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

var _abstractBitJson;

function _load_abstractBitJson() {
  return _abstractBitJson = _interopRequireDefault(require('./abstract-bit-json'));
}

var _exceptions;

function _load_exceptions() {
  return _exceptions = require('./exceptions');
}

var _constants;

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

var _filterObject;

function _load_filterObject() {
  return _filterObject = _interopRequireDefault(require('../../utils/filter-object'));
}

var _logger;

function _load_logger() {
  return _logger = _interopRequireDefault(require('../../logger/logger'));
}

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

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

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 DEFAULT_USE_WORKSPACES = false;
var DEFAULT_MANAGE_WORKSPACES = true;
var DEFAULT_SAVE_DEPENDENCIES_AS_COMPONENTS = false;

var ConsumerBitJson = function (_AbstractBitJson) {
  _inherits(ConsumerBitJson, _AbstractBitJson);

  // Enables integration with Yarn Workspaces
  // package manager client to use
  // save hub dependencies as bit components rather than npm packages
  function ConsumerBitJson(_ref) {
    var compiler = _ref.compiler,
        tester = _ref.tester,
        dependencies = _ref.dependencies,
        _ref$saveDependencies = _ref.saveDependenciesAsComponents,
        saveDependenciesAsComponents = _ref$saveDependencies === undefined ? DEFAULT_SAVE_DEPENDENCIES_AS_COMPONENTS : _ref$saveDependencies,
        lang = _ref.lang,
        distTarget = _ref.distTarget,
        distEntry = _ref.distEntry,
        _ref$componentsDefaul = _ref.componentsDefaultDirectory,
        componentsDefaultDirectory = _ref$componentsDefaul === undefined ? (_constants || _load_constants()).DEFAULT_COMPONENTS_DIR_PATH : _ref$componentsDefaul,
        _ref$dependenciesDire = _ref.dependenciesDirectory,
        dependenciesDirectory = _ref$dependenciesDire === undefined ? (_constants || _load_constants()).DEFAULT_DEPENDENCIES_DIR_PATH : _ref$dependenciesDire,
        _ref$ejectedEnvsDirec = _ref.ejectedEnvsDirectory,
        ejectedEnvsDirectory = _ref$ejectedEnvsDirec === undefined ? (_constants || _load_constants()).DEFAULT_EJECTED_ENVS_DIR_PATH : _ref$ejectedEnvsDirec,
        bindingPrefix = _ref.bindingPrefix,
        extensions = _ref.extensions,
        _ref$packageManager = _ref.packageManager,
        packageManager = _ref$packageManager === undefined ? (_constants || _load_constants()).DEFAULT_PACKAGE_MANAGER : _ref$packageManager,
        packageManagerArgs = _ref.packageManagerArgs,
        packageManagerProcessOptions = _ref.packageManagerProcessOptions,
        _ref$useWorkspaces = _ref.useWorkspaces,
        useWorkspaces = _ref$useWorkspaces === undefined ? DEFAULT_USE_WORKSPACES : _ref$useWorkspaces,
        _ref$manageWorkspaces = _ref.manageWorkspaces,
        manageWorkspaces = _ref$manageWorkspaces === undefined ? DEFAULT_MANAGE_WORKSPACES : _ref$manageWorkspaces,
        resolveModules = _ref.resolveModules;

    _classCallCheck(this, ConsumerBitJson);

    var _this = _possibleConstructorReturn(this, (ConsumerBitJson.__proto__ || Object.getPrototypeOf(ConsumerBitJson)).call(this, { compiler, tester, dependencies, lang, bindingPrefix, extensions }));

    _this.distTarget = distTarget;
    _this.distEntry = distEntry;
    _this.componentsDefaultDirectory = componentsDefaultDirectory;
    _this.dependenciesDirectory = dependenciesDirectory;
    _this.ejectedEnvsDirectory = ejectedEnvsDirectory;
    _this.saveDependenciesAsComponents = saveDependenciesAsComponents;
    _this.packageManager = packageManager;
    _this.packageManagerArgs = packageManagerArgs;
    _this.packageManagerProcessOptions = packageManagerProcessOptions;
    _this.useWorkspaces = useWorkspaces;
    _this.manageWorkspaces = manageWorkspaces;
    _this.resolveModules = resolveModules;
    return _this;
  } // manage workspaces with yarn
  // package manager process options
  // package manager client to use
  // path where to store build artifacts
  // path to remove while storing build artifacts. If, for example the code is in 'src' directory, and the component
  // is-string is in src/components/is-string, the dists files will be in dists/component/is-string (without the 'src')


  _createClass(ConsumerBitJson, [{
    key: 'toPlainObject',
    value: function toPlainObject() {
      var superObject = _get(ConsumerBitJson.prototype.__proto__ || Object.getPrototypeOf(ConsumerBitJson.prototype), 'toPlainObject', this).call(this);
      var consumerObject = (_ramda || _load_ramda()).default.merge(superObject, {
        componentsDefaultDirectory: this.componentsDefaultDirectory,
        dependenciesDirectory: this.dependenciesDirectory,
        ejectedEnvsDirectory: this.ejectedEnvsDirectory,
        saveDependenciesAsComponents: this.saveDependenciesAsComponents,
        packageManager: this.packageManager,
        packageManagerArgs: this.packageManagerArgs,
        packageManagerProcessOptions: this.packageManagerProcessOptions,
        useWorkspaces: this.useWorkspaces,
        manageWorkspaces: this.manageWorkspaces,
        resolveModules: this.resolveModules
      });
      if (this.distEntry || this.distTarget) {
        var dist = {};
        if (this.distEntry) dist.entry = this.distEntry;
        if (this.distTarget) dist.target = this.distTarget;
        consumerObject = (_ramda || _load_ramda()).default.merge(consumerObject, { dist });
      }

      var isPropDefault = function isPropDefault(val, key) {
        if (key === 'dependenciesDirectory') return val !== (_constants || _load_constants()).DEFAULT_DEPENDENCIES_DIR_PATH;
        if (key === 'ejectedEnvsDirectory') return val !== (_constants || _load_constants()).DEFAULT_EJECTED_ENVS_DIR_PATH;
        if (key === 'useWorkspaces') return val !== DEFAULT_USE_WORKSPACES;
        if (key === 'manageWorkspaces') return val !== DEFAULT_MANAGE_WORKSPACES;
        if (key === 'saveDependenciesAsComponents') return val !== DEFAULT_SAVE_DEPENDENCIES_AS_COMPONENTS;
        if (key === 'resolveModules') return !(_ramda || _load_ramda()).default.isEmpty(val);
        return true;
      };

      return (0, (_filterObject || _load_filterObject()).default)(consumerObject, isPropDefault);
    }
  }], [{
    key: 'create',
    value: function create() {
      return new ConsumerBitJson({});
    }
  }, {
    key: 'ensure',
    value: function () {
      var _ref2 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee(dirPath) {
        var consumerBitJson;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _context.prev = 0;
                _context.next = 3;
                return this.load(dirPath);

              case 3:
                consumerBitJson = _context.sent;
                return _context.abrupt('return', consumerBitJson);

              case 7:
                _context.prev = 7;
                _context.t0 = _context['catch'](0);
                return _context.abrupt('return', this.create());

              case 10:
              case 'end':
                return _context.stop();
            }
          }
        }, _callee, this, [[0, 7]]);
      }));

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

      return ensure;
    }()
  }, {
    key: 'reset',
    value: function () {
      var _ref3 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee3(dirPath, resetHard) {
        var _this2 = this;

        var deleteBitJsonFile;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                deleteBitJsonFile = function () {
                  var _ref4 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee2() {
                    var bitJsonPath;
                    return (_regenerator || _load_regenerator()).default.wrap(function _callee2$(_context2) {
                      while (1) {
                        switch (_context2.prev = _context2.next) {
                          case 0:
                            bitJsonPath = (_abstractBitJson || _load_abstractBitJson()).default.composePath(dirPath);

                            (_logger || _load_logger()).default.info(`deleting the consumer bit.json file at ${bitJsonPath}`);
                            _context2.next = 4;
                            return (_fsExtra || _load_fsExtra()).default.remove(bitJsonPath);

                          case 4:
                          case 'end':
                            return _context2.stop();
                        }
                      }
                    }, _callee2, _this2);
                  }));

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

                if (!resetHard) {
                  _context3.next = 4;
                  break;
                }

                _context3.next = 4;
                return deleteBitJsonFile();

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

      function reset(_x2, _x3) {
        return _ref3.apply(this, arguments);
      }

      return reset;
    }()
  }, {
    key: 'fromPlainObject',
    value: function fromPlainObject(object) {
      var sources = object.sources,
          env = object.env,
          dependencies = object.dependencies,
          lang = object.lang,
          componentsDefaultDirectory = object.componentsDefaultDirectory,
          dependenciesDirectory = object.dependenciesDirectory,
          ejectedEnvsDirectory = object.ejectedEnvsDirectory,
          dist = object.dist,
          bindingPrefix = object.bindingPrefix,
          extensions = object.extensions,
          saveDependenciesAsComponents = object.saveDependenciesAsComponents,
          packageManager = object.packageManager,
          packageManagerArgs = object.packageManagerArgs,
          packageManagerProcessOptions = object.packageManagerProcessOptions,
          useWorkspaces = object.useWorkspaces,
          manageWorkspaces = object.manageWorkspaces,
          resolveModules = object.resolveModules;


      return new ConsumerBitJson({
        compiler: (_ramda || _load_ramda()).default.propOr(undefined, 'compiler', env),
        tester: (_ramda || _load_ramda()).default.propOr(undefined, 'tester', env),
        lang,
        bindingPrefix,
        extensions,
        dependencies,
        saveDependenciesAsComponents,
        componentsDefaultDirectory,
        dependenciesDirectory,
        ejectedEnvsDirectory,
        packageManager,
        packageManagerArgs,
        packageManagerProcessOptions,
        useWorkspaces,
        manageWorkspaces,
        resolveModules,
        distTarget: (_ramda || _load_ramda()).default.propOr(undefined, 'target', dist),
        distEntry: (_ramda || _load_ramda()).default.propOr(undefined, 'entry', dist)
      });
    }
  }, {
    key: 'load',
    value: function () {
      var _ref5 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee4(dirPath) {
        var isExisting, bitJsonPath, file, consumerBitJson;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                _context4.next = 2;
                return (_abstractBitJson || _load_abstractBitJson()).default.hasExisting(dirPath);

              case 2:
                isExisting = _context4.sent;

                if (isExisting) {
                  _context4.next = 5;
                  break;
                }

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

              case 5:
                bitJsonPath = (_abstractBitJson || _load_abstractBitJson()).default.composePath(dirPath);
                _context4.prev = 6;
                _context4.next = 9;
                return (_fsExtra || _load_fsExtra()).default.readJson(bitJsonPath);

              case 9:
                file = _context4.sent;
                consumerBitJson = this.fromPlainObject(file);

                consumerBitJson.path = bitJsonPath;
                return _context4.abrupt('return', consumerBitJson);

              case 15:
                _context4.prev = 15;
                _context4.t0 = _context4['catch'](6);
                throw new (_exceptions || _load_exceptions()).InvalidBitJson(bitJsonPath);

              case 18:
              case 'end':
                return _context4.stop();
            }
          }
        }, _callee4, this, [[6, 15]]);
      }));

      function load(_x4) {
        return _ref5.apply(this, arguments);
      }

      return load;
    }()
  }]);

  return ConsumerBitJson;
}((_abstractBitJson || _load_abstractBitJson()).default);

exports.default = ConsumerBitJson;