'use strict';

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

var _regenerator;

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

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

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

var _version;

function _load_version() {
  return _version = _interopRequireDefault(require('./models/version'));
}

var _bitId;

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

var _scope;

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

var _repository;

function _load_repository() {
  return _repository = _interopRequireDefault(require('./objects/repository'));
}

var _versionDependencies;

function _load_versionDependencies() {
  return _versionDependencies = _interopRequireDefault(require('./version-dependencies'));
}

var _componentObjects;

function _load_componentObjects() {
  return _componentObjects = _interopRequireDefault(require('./component-objects'));
}

var _logger;

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

var _component2;

function _load_component2() {
  return _component2 = _interopRequireDefault(require('../consumer/component'));
}

var _generalError;

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

var _exceptions;

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

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

var ComponentVersion = function () {
  function ComponentVersion(component, version) {
    _classCallCheck(this, ComponentVersion);

    this.component = component;
    this.version = version;
  }

  _createClass(ComponentVersion, [{
    key: 'getVersion',
    value: function getVersion(repository) {
      return this.component.loadVersion(this.version, repository);
    }
  }, {
    key: 'flattenedDependencies',
    value: function flattenedDependencies(repository) {
      return this.getVersion(repository).then(function (version) {
        return version.flattenedDependencies;
      });
    }
  }, {
    key: 'flattenedDevDependencies',
    value: function flattenedDevDependencies(repository) {
      return this.getVersion(repository).then(function (version) {
        return version.flattenedDevDependencies;
      });
    }
  }, {
    key: 'flattenedCompilerDependencies',
    value: function flattenedCompilerDependencies(repository) {
      return this.getVersion(repository).then(function (version) {
        return version.flattenedCompilerDependencies;
      });
    }
  }, {
    key: 'flattenedTesterDependencies',
    value: function flattenedTesterDependencies(repository) {
      return this.getVersion(repository).then(function (version) {
        return version.flattenedTesterDependencies;
      });
    }
  }, {
    key: 'toId',
    value: function toId() {
      return new (_bitId || _load_bitId()).BitId({
        scope: this.component.scope,
        name: this.component.name,
        version: this.version
      });
    }
  }, {
    key: 'toVersionDependencies',
    value: function () {
      var _ref = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee(scope, source) {
        var _this = this;

        var version, dependencies, devDependencies, compilerDependencies, testerDependencies;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _context.next = 2;
                return this.getVersion(scope.objects);

              case 2:
                version = _context.sent;

                if (version) {
                  _context.next = 8;
                  break;
                }

                (_logger || _load_logger()).default.debug(`toVersionDependencies, component ${this.component.id().toString()}, version ${this.version} not found, going to fetch from a remote`);

                if (!(this.component.scope === scope.name)) {
                  _context.next = 7;
                  break;
                }

                throw new (_generalError || _load_generalError()).default(`Version ${this.version} of ${this.component.id().toString()} was not found in scope ${scope.name}`);

              case 7:
                return _context.abrupt('return', scope.remotes().then(function (remotes) {
                  var src = _this.id;
                  src.scope = source;
                  return scope.getExternal({ id: src, remotes, localFetch: false });
                }));

              case 8:

                (_logger || _load_logger()).default.debug(`toVersionDependencies, component ${this.component.id().toString()}, version ${this.version} found, going to collect its dependencies`);
                _context.next = 11;
                return scope.importManyOnes(version.flattenedDependencies);

              case 11:
                dependencies = _context.sent;
                _context.next = 14;
                return scope.importManyOnes(version.flattenedDevDependencies);

              case 14:
                devDependencies = _context.sent;
                _context.next = 17;
                return scope.importManyOnes(version.flattenedCompilerDependencies);

              case 17:
                compilerDependencies = _context.sent;
                _context.next = 20;
                return scope.importManyOnes(version.flattenedTesterDependencies);

              case 20:
                testerDependencies = _context.sent;
                return _context.abrupt('return', new (_versionDependencies || _load_versionDependencies()).default(this, dependencies, devDependencies, compilerDependencies, testerDependencies, source));

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

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

      return toVersionDependencies;
    }()
  }, {
    key: 'toConsumer',
    value: function toConsumer(repo) {
      return this.component.toConsumerComponent(this.version, this.component.scope, repo);
    }
  }, {
    key: 'toObjects',
    value: function () {
      var _ref2 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee2(repo) {
        var version, _ref3, _ref4, compObject, objects, versionBuffer, scopeMeta, originalVersionHash, currentVersionHash;

        return (_regenerator || _load_regenerator()).default.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _context2.next = 2;
                return this.getVersion(repo);

              case 2:
                version = _context2.sent;

                if (version) {
                  _context2.next = 5;
                  break;
                }

                throw new (_generalError || _load_generalError()).default(`failed loading version ${this.version} of ${this.component.id()}`);

              case 5:
                _context2.prev = 5;
                _context2.next = 8;
                return Promise.all([this.component.asRaw(repo), version.collectRaw(repo), version.asRaw(repo), repo.getScopeMetaObject()]);

              case 8:
                _ref3 = _context2.sent;
                _ref4 = _slicedToArray(_ref3, 4);
                compObject = _ref4[0];
                objects = _ref4[1];
                versionBuffer = _ref4[2];
                scopeMeta = _ref4[3];
                return _context2.abrupt('return', new (_componentObjects || _load_componentObjects()).default(compObject, objects.concat([versionBuffer, scopeMeta])));

              case 17:
                _context2.prev = 17;
                _context2.t0 = _context2['catch'](5);

                (_logger || _load_logger()).default.error(_context2.t0);
                originalVersionHash = this.component.versions[this.version].toString();
                currentVersionHash = version.hash().toString();

                if (!(originalVersionHash !== currentVersionHash)) {
                  _context2.next = 24;
                  break;
                }

                throw new (_exceptions || _load_exceptions()).HashMismatch(this.component.id(), this.version, originalVersionHash, currentVersionHash);

              case 24:
                throw _context2.t0;

              case 25:
              case 'end':
                return _context2.stop();
            }
          }
        }, _callee2, this, [[5, 17]]);
      }));

      function toObjects(_x3) {
        return _ref2.apply(this, arguments);
      }

      return toObjects;
    }()
  }, {
    key: 'id',
    get: function get() {
      return this.toId();
    }
  }]);

  return ComponentVersion;
}();

exports.default = ComponentVersion;