'use strict';

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

var _regenerator;

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

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

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 _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 _path;

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

var _ramda;

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

var _stringFormat;

function _load_stringFormat() {
  return _stringFormat = _interopRequireDefault(require('string-format'));
}

var _baseExtension;

function _load_baseExtension() {
  return _baseExtension = _interopRequireDefault(require('./base-extension'));
}

var _scope;

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

var _bitId;

function _load_bitId() {
  return _bitId = _interopRequireDefault(require('../bit-id/bit-id'));
}

var _extensionFile;

function _load_extensionFile() {
  return _extensionFile = _interopRequireDefault(require('./extension-file'));
}

var _objects;

function _load_objects() {
  return _objects = require('../scope/objects');
}

var _utils;

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

var _scope2;

function _load_scope2() {
  return _scope2 = require('../scope');
}

var _analytics;

function _load_analytics() {
  return _analytics = require('../analytics/analytics');
}

var _extensionGetDynamicPackagesError;

function _load_extensionGetDynamicPackagesError() {
  return _extensionGetDynamicPackagesError = _interopRequireDefault(require('./exceptions/extension-get-dynamic-packages-error'));
}

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

// Couldn't find a good way to do this with consts
// see https://github.com/facebook/flow/issues/627
// I would expect something like:
// type EnvType = CompilerEnvType | TesterEnvType would work
var EnvExtension = function (_BaseExtension) {
  _inherits(EnvExtension, _BaseExtension);

  _createClass(EnvExtension, [{
    key: 'action',


    /**
     * Return the action
     */
    get: function get() {
      if (this.script && this.script.action && typeof this.script.action === 'function') {
        return this.script.action;
      }
      return undefined;
    }

    /**
     * return old actions (to support old compilers / testers which uses run / compile functions)
     */

  }, {
    key: 'oldAction',
    get: function get() {
      if (this.script && this.script.run && typeof this.script.run === 'function') {
        return this.script.run;
      }
      if (this.script && this.script.compile && typeof this.script.compile === 'function') {
        return this.script.compile;
      }
      return undefined;
    }
  }]);

  function EnvExtension(extensionProps) {
    _classCallCheck(this, EnvExtension);

    var _this = _possibleConstructorReturn(this, (EnvExtension.__proto__ || Object.getPrototypeOf(EnvExtension)).call(this, extensionProps));

    _this.envType = extensionProps.envType;
    _this.dynamicPackageDependencies = extensionProps.dynamicPackageDependencies;
    _this.files = extensionProps.files;
    return _this;
  }

  _createClass(EnvExtension, [{
    key: 'install',
    value: function () {
      var _ref = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee(scope, opts, context) {
        var dependentId, installOpts, installResult;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                (_analytics || _load_analytics()).Analytics.addBreadCrumb('env-extension', 'install env extension');

                // Skip the installation in case of using specific file
                // options.file usually used for develop your extension

                if (!this.options.file) {
                  _context.next = 3;
                  break;
                }

                return _context.abrupt('return', undefined);

              case 3:
                dependentId = (_ramda || _load_ramda()).default.path(['dependentId'], context);
                installOpts = _extends({
                  ids: [{ componentId: (_bitId || _load_bitId()).default.parse(this.name), type: this.envType.toLowerCase() }],
                  dependentId
                }, opts);
                _context.next = 7;
                return scope.installEnvironment(installOpts);

              case 7:
                installResult = _context.sent;

                this.setExtensionPathInScope(scope.getPath());
                _context.next = 11;
                return this.reload(scope.getPath(), context);

              case 11:
                return _context.abrupt('return', installResult);

              case 12:
              case 'end':
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function install(_x, _x2, _x3) {
        return _ref.apply(this, arguments);
      }

      return install;
    }()
  }, {
    key: 'toModelObject',
    value: function toModelObject() {
      (_analytics || _load_analytics()).Analytics.addBreadCrumb('env-extension', 'toModelObject');
      var baseObject = _get(EnvExtension.prototype.__proto__ || Object.getPrototypeOf(EnvExtension.prototype), 'toModelObject', this).call(this);
      var files = this.files.map(function (file) {
        return file.toModelObject();
      });
      var modelObject = _extends({ files }, baseObject);
      return modelObject;
    }
  }, {
    key: 'toObject',
    value: function toObject() {
      (_analytics || _load_analytics()).Analytics.addBreadCrumb('env-extension', 'toObject');
      var baseObject = _get(EnvExtension.prototype.__proto__ || Object.getPrototypeOf(EnvExtension.prototype), 'toObject', this).call(this);
      var files = this.files;
      var object = _extends({ files }, baseObject);
      return object;
    }

    /**
     * Get a bit.json representation of the env instance
     * @param {string} ejectedEnvDirectory - The base path of where the env config files are stored
     * $FlowFixMe seems to be an issue opened for this https://github.com/facebook/flow/issues/4953
     */

  }, {
    key: 'toBitJsonObject',
    value: function toBitJsonObject(ejectedEnvDirectory) {
      (_analytics || _load_analytics()).Analytics.addBreadCrumb('env-extension', 'toBitJsonObject');
      var files = {};
      this.files.forEach(function (file) {
        var relativePath = (0, (_utils || _load_utils()).pathJoinLinux)(ejectedEnvDirectory, file.name);
        files[file.name] = `./${relativePath}`;
      });
      var envVal = {
        rawConfig: this.dynamicConfig,
        options: this.options,
        files
      };
      return {
        [this.name]: envVal
      };
    }

    /**
     * Write the env files to the file system according to the template dir
     * used for ejecting env for imported component
     * @param {*} param0
     */

  }, {
    key: 'writeFilesToFs',
    value: function () {
      var _ref3 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee2(_ref2) {
        var bitDir = _ref2.bitDir,
            ejectedEnvsDirectory = _ref2.ejectedEnvsDirectory,
            envType = _ref2.envType;
        var resolvedEjectedEnvsDirectory, newBase, writeP;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                (_analytics || _load_analytics()).Analytics.addBreadCrumb('env-extension', 'writeFilesToFs');
                resolvedEjectedEnvsDirectory = (0, (_stringFormat || _load_stringFormat()).default)(ejectedEnvsDirectory, { envType });
                newBase = (_path || _load_path()).default.join(bitDir, resolvedEjectedEnvsDirectory);
                writeP = this.files.map(function (file) {
                  file.updatePaths({ newBase, newRelative: file.name });
                  return file.write();
                });
                _context2.next = 6;
                return Promise.all(writeP);

              case 6:
                return _context2.abrupt('return', resolvedEjectedEnvsDirectory);

              case 7:
              case 'end':
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }));

      function writeFilesToFs(_x4) {
        return _ref3.apply(this, arguments);
      }

      return writeFilesToFs;
    }()
  }, {
    key: 'reload',
    value: function () {
      var _ref4 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee3(scopePath, context) {
        var throws, dynamicPackageDependencies;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                (_analytics || _load_analytics()).Analytics.addBreadCrumb('env-extension', 'reload');
                if (context) {
                  this.context = context;
                }
                throws = true;
                _context3.next = 5;
                return _get(EnvExtension.prototype.__proto__ || Object.getPrototypeOf(EnvExtension.prototype), 'reload', this).call(this, scopePath, { throws });

              case 5:
                _context3.next = 7;
                return EnvExtension.loadDynamicPackageDependencies(this);

              case 7:
                dynamicPackageDependencies = _context3.sent;

                this.dynamicPackageDependencies = dynamicPackageDependencies;

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

      function reload(_x5, _x6) {
        return _ref4.apply(this, arguments);
      }

      return reload;
    }()

    /**
     * Loading from props (usually from bit.json)
     * @param {*} props
     * $FlowFixMe seems to be an issue opened for this https://github.com/facebook/flow/issues/4953
     */

  }], [{
    key: 'load',
    value: function () {
      var _ref5 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee4(props) {
        var baseExtensionProps, files, envExtensionProps, dynamicPackageDependencies;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                (_analytics || _load_analytics()).Analytics.addBreadCrumb('env-extension', 'load');
                _context4.next = 3;
                return _get(EnvExtension.__proto__ || Object.getPrototypeOf(EnvExtension), 'load', this).call(this, props);

              case 3:
                baseExtensionProps = _context4.sent;
                _context4.next = 6;
                return (_extensionFile || _load_extensionFile()).default.loadFromBitJsonObject(props.files, props.consumerPath, props.bitJsonPath);

              case 6:
                files = _context4.sent;
                envExtensionProps = _extends({ envType: props.envType, files }, baseExtensionProps);
                _context4.next = 10;
                return EnvExtension.loadDynamicPackageDependencies(envExtensionProps);

              case 10:
                dynamicPackageDependencies = _context4.sent;

                envExtensionProps.dynamicPackageDependencies = dynamicPackageDependencies;
                return _context4.abrupt('return', envExtensionProps);

              case 13:
              case 'end':
                return _context4.stop();
            }
          }
        }, _callee4, this);
      }));

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

      return load;
    }()
  }, {
    key: 'loadDynamicPackageDependencies',
    value: function () {
      var _ref6 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee5(envExtensionProps) {
        var getDynamicPackageDependencies, _dynamicPackageDependencies;

        return (_regenerator || _load_regenerator()).default.wrap(function _callee5$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                (_analytics || _load_analytics()).Analytics.addBreadCrumb('env-extension', 'loadDynamicPackageDependencies');
                getDynamicPackageDependencies = (_ramda || _load_ramda()).default.path(['script', 'getDynamicPackageDependencies'], envExtensionProps);

                if (!(getDynamicPackageDependencies && typeof getDynamicPackageDependencies === 'function')) {
                  _context5.next = 13;
                  break;
                }

                _context5.prev = 3;
                _context5.next = 6;
                return getDynamicPackageDependencies({
                  rawConfig: envExtensionProps.rawConfig,
                  dynamicConfig: envExtensionProps.dynamicConfig,
                  configFiles: envExtensionProps.files,
                  context: envExtensionProps.context
                });

              case 6:
                _dynamicPackageDependencies = _context5.sent;
                return _context5.abrupt('return', _dynamicPackageDependencies);

              case 10:
                _context5.prev = 10;
                _context5.t0 = _context5['catch'](3);
                throw new (_extensionGetDynamicPackagesError || _load_extensionGetDynamicPackagesError()).default(_context5.t0, envExtensionProps.name);

              case 13:
                return _context5.abrupt('return', undefined);

              case 14:
              case 'end':
                return _context5.stop();
            }
          }
        }, _callee5, this, [[3, 10]]);
      }));

      function loadDynamicPackageDependencies(_x8) {
        return _ref6.apply(this, arguments);
      }

      return loadDynamicPackageDependencies;
    }()

    /**
     * $FlowFixMe seems to be an issue opened for this https://github.com/facebook/flow/issues/4953
     */

  }, {
    key: 'loadFromModelObject',
    value: function () {
      var _ref7 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee6(
      // $FlowFixMe
      modelObject, repository) {
        var baseExtensionProps, files, loadFilesP, envExtensionProps;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                (_analytics || _load_analytics()).Analytics.addBreadCrumb('env-extension', 'loadFromModelObject');
                // $FlowFixMe
                baseExtensionProps = _get(EnvExtension.__proto__ || Object.getPrototypeOf(EnvExtension), 'loadFromModelObject', this).call(this, modelObject);
                files = [];

                if (!(modelObject.files && !(_ramda || _load_ramda()).default.isEmpty(modelObject.files))) {
                  _context6.next = 8;
                  break;
                }

                loadFilesP = modelObject.files.map(function (file) {
                  return (_extensionFile || _load_extensionFile()).default.loadFromExtensionFileModel(file, repository);
                });
                _context6.next = 7;
                return Promise.all(loadFilesP);

              case 7:
                files = _context6.sent;

              case 8:
                envExtensionProps = _extends({ envType: modelObject.envType, files }, baseExtensionProps);
                return _context6.abrupt('return', envExtensionProps);

              case 10:
              case 'end':
                return _context6.stop();
            }
          }
        }, _callee6, this);
      }));

      function loadFromModelObject(_x9, _x10) {
        return _ref7.apply(this, arguments);
      }

      return loadFromModelObject;
    }()
  }]);

  return EnvExtension;
}((_baseExtension || _load_baseExtension()).default);

exports.default = EnvExtension;