"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _rxjs = require("rxjs");

var _helpers = require("../utils/helpers");

var _mdSeedRunnerError = _interopRequireDefault(require("./md-seed-runner-error"));

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

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }

function _iterableToArrayLimit(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"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var MdSeedRunner =
/*#__PURE__*/
function () {
  /**
   * Creates MdSeedRunner
   * @param {AsyncFunction} connect     Connect to mongodb implementation
   * @param {AsyncFunction} dropdb      Drop/Clear the database implementation
   * @param {Object}        seedersList key=Seeder name | value=Seeder implementation
   */
  function MdSeedRunner(_ref) {
    var connect = _ref.connect,
        dropdb = _ref.dropdb,
        seedersList = _ref.seedersList;

    _classCallCheck(this, MdSeedRunner);

    this.connect = connect;
    this.dropdb = dropdb;
    this.seedersList = seedersList;
    this.subject = new _rxjs.Subject();
  }

  _createClass(MdSeedRunner, [{
    key: "run",
    value: function run() {
      var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          _ref2$selectedSeeders = _ref2.selectedSeeders,
          selectedSeeders = _ref2$selectedSeeders === void 0 ? [] : _ref2$selectedSeeders,
          _ref2$dropDatabase = _ref2.dropDatabase,
          dropDatabase = _ref2$dropDatabase === void 0 ? false : _ref2$dropDatabase;

      this._run({
        selectedSeeders: selectedSeeders,
        dropDatabase: dropDatabase
      });

      return this.subject.asObservable();
    }
    /*
      Private methods
     */

  }, {
    key: "_run",
    value: function () {
      var _run2 = _asyncToGenerator(
      /*#__PURE__*/
      regeneratorRuntime.mark(function _callee(_ref3) {
        var selectedSeeders, dropDatabase, _MdSeedRunner$operati, START, SUCCESS, ERROR, _error$type, type, _error$payload, payload;

        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                selectedSeeders = _ref3.selectedSeeders, dropDatabase = _ref3.dropDatabase;
                _MdSeedRunner$operati = MdSeedRunner.operations, START = _MdSeedRunner$operati.START, SUCCESS = _MdSeedRunner$operati.SUCCESS, ERROR = _MdSeedRunner$operati.ERROR;
                _context.prev = 2;
                this.subject.next({
                  type: START,
                  payload: {
                    selectedSeeders: selectedSeeders,
                    dropDatabase: dropDatabase
                  }
                });
                _context.next = 6;
                return this._connectToMongodb();

              case 6:
                if (!dropDatabase) {
                  _context.next = 9;
                  break;
                }

                _context.next = 9;
                return this._dropDatabase();

              case 9:
                _context.next = 11;
                return this._runSeeders(selectedSeeders);

              case 11:
                this.subject.next({
                  type: SUCCESS,
                  payload: {
                    selectedSeeders: selectedSeeders,
                    dropDatabase: dropDatabase
                  }
                });
                this.subject.complete();
                _context.next = 19;
                break;

              case 15:
                _context.prev = 15;
                _context.t0 = _context["catch"](2);
                _error$type = _context.t0.type, type = _error$type === void 0 ? ERROR : _error$type, _error$payload = _context.t0.payload, payload = _error$payload === void 0 ? {
                  error: _context.t0
                } : _error$payload;
                this.subject.error({
                  type: type,
                  payload: payload
                });

              case 19:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this, [[2, 15]]);
      }));

      function _run(_x) {
        return _run2.apply(this, arguments);
      }

      return _run;
    }()
  }, {
    key: "_connectToMongodb",
    value: function () {
      var _connectToMongodb2 = _asyncToGenerator(
      /*#__PURE__*/
      regeneratorRuntime.mark(function _callee2() {
        var _MdSeedRunner$operati2, MONGOOSE_CONNECT_START, MONGOOSE_CONNECT_SUCCESS, MONGOOSE_CONNECT_ERROR;

        return regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _MdSeedRunner$operati2 = MdSeedRunner.operations, MONGOOSE_CONNECT_START = _MdSeedRunner$operati2.MONGOOSE_CONNECT_START, MONGOOSE_CONNECT_SUCCESS = _MdSeedRunner$operati2.MONGOOSE_CONNECT_SUCCESS, MONGOOSE_CONNECT_ERROR = _MdSeedRunner$operati2.MONGOOSE_CONNECT_ERROR;
                _context2.prev = 1;
                this.subject.next({
                  type: MONGOOSE_CONNECT_START
                });
                _context2.next = 5;
                return this.connect();

              case 5:
                this.subject.next({
                  type: MONGOOSE_CONNECT_SUCCESS
                });
                _context2.next = 11;
                break;

              case 8:
                _context2.prev = 8;
                _context2.t0 = _context2["catch"](1);
                throw new _mdSeedRunnerError["default"]({
                  type: MONGOOSE_CONNECT_ERROR,
                  error: _context2.t0
                });

              case 11:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this, [[1, 8]]);
      }));

      function _connectToMongodb() {
        return _connectToMongodb2.apply(this, arguments);
      }

      return _connectToMongodb;
    }()
  }, {
    key: "_dropDatabase",
    value: function () {
      var _dropDatabase2 = _asyncToGenerator(
      /*#__PURE__*/
      regeneratorRuntime.mark(function _callee3() {
        var _MdSeedRunner$operati3, MONGOOSE_DROP_START, MONGOOSE_DROP_SUCCESS, MONGOOSE_DROP_ERROR;

        return regeneratorRuntime.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                _MdSeedRunner$operati3 = MdSeedRunner.operations, MONGOOSE_DROP_START = _MdSeedRunner$operati3.MONGOOSE_DROP_START, MONGOOSE_DROP_SUCCESS = _MdSeedRunner$operati3.MONGOOSE_DROP_SUCCESS, MONGOOSE_DROP_ERROR = _MdSeedRunner$operati3.MONGOOSE_DROP_ERROR;
                _context3.prev = 1;
                this.subject.next({
                  type: MONGOOSE_DROP_START
                });
                _context3.next = 5;
                return this.dropdb();

              case 5:
                this.subject.next({
                  type: MONGOOSE_DROP_SUCCESS
                });
                _context3.next = 11;
                break;

              case 8:
                _context3.prev = 8;
                _context3.t0 = _context3["catch"](1);
                throw new _mdSeedRunnerError["default"]({
                  type: MONGOOSE_DROP_ERROR,
                  error: _context3.t0
                });

              case 11:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3, this, [[1, 8]]);
      }));

      function _dropDatabase() {
        return _dropDatabase2.apply(this, arguments);
      }

      return _dropDatabase;
    }()
  }, {
    key: "_runSeeders",
    value: function () {
      var _runSeeders2 = _asyncToGenerator(
      /*#__PURE__*/
      regeneratorRuntime.mark(function _callee4(selectedSeeders) {
        var _MdSeedRunner$operati4, ALL_SEEDERS_START, ALL_SEEDERS_FINISH, seeders, _i, _Object$entries, _Object$entries$_i, name, Seeder;

        return regeneratorRuntime.wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                _MdSeedRunner$operati4 = MdSeedRunner.operations, ALL_SEEDERS_START = _MdSeedRunner$operati4.ALL_SEEDERS_START, ALL_SEEDERS_FINISH = _MdSeedRunner$operati4.ALL_SEEDERS_FINISH;
                seeders = this._loadSelectedSeeders(selectedSeeders);
                this.subject.next({
                  type: ALL_SEEDERS_START,
                  payload: {
                    seeders: Object.keys(seeders)
                  }
                });
                _i = 0, _Object$entries = Object.entries(seeders);

              case 4:
                if (!(_i < _Object$entries.length)) {
                  _context4.next = 11;
                  break;
                }

                _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2), name = _Object$entries$_i[0], Seeder = _Object$entries$_i[1];
                _context4.next = 8;
                return this._runSeeder({
                  name: name,
                  Seeder: Seeder
                });

              case 8:
                _i++;
                _context4.next = 4;
                break;

              case 11:
                this.subject.next({
                  type: ALL_SEEDERS_FINISH,
                  payload: {
                    seeders: Object.keys(seeders)
                  }
                });

              case 12:
              case "end":
                return _context4.stop();
            }
          }
        }, _callee4, this);
      }));

      function _runSeeders(_x2) {
        return _runSeeders2.apply(this, arguments);
      }

      return _runSeeders;
    }()
  }, {
    key: "_runSeeder",
    value: function () {
      var _runSeeder2 = _asyncToGenerator(
      /*#__PURE__*/
      regeneratorRuntime.mark(function _callee5(_ref4) {
        var Seeder, name, _MdSeedRunner$operati5, SEEDER_START, SEEDER_SUCCESS, SEEDER_ERROR, seeder, results;

        return regeneratorRuntime.wrap(function _callee5$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                Seeder = _ref4.Seeder, name = _ref4.name;
                _MdSeedRunner$operati5 = MdSeedRunner.operations, SEEDER_START = _MdSeedRunner$operati5.SEEDER_START, SEEDER_SUCCESS = _MdSeedRunner$operati5.SEEDER_SUCCESS, SEEDER_ERROR = _MdSeedRunner$operati5.SEEDER_ERROR;
                _context5.prev = 2;
                this.subject.next({
                  type: SEEDER_START,
                  payload: {
                    name: name
                  }
                });
                seeder = new Seeder();
                _context5.next = 7;
                return seeder.seed();

              case 7:
                results = _context5.sent;
                this.subject.next({
                  type: SEEDER_SUCCESS,
                  payload: {
                    name: name,
                    results: results
                  }
                });
                _context5.next = 14;
                break;

              case 11:
                _context5.prev = 11;
                _context5.t0 = _context5["catch"](2);
                throw new _mdSeedRunnerError["default"]({
                  type: SEEDER_ERROR,
                  payload: {
                    name: name
                  },
                  error: _context5.t0
                });

              case 14:
              case "end":
                return _context5.stop();
            }
          }
        }, _callee5, this, [[2, 11]]);
      }));

      function _runSeeder(_x3) {
        return _runSeeder2.apply(this, arguments);
      }

      return _runSeeder;
    }()
  }, {
    key: "_loadSelectedSeeders",
    value: function _loadSelectedSeeders(selectedSeeders) {
      if (selectedSeeders && selectedSeeders.length > 0) {
        return (0, _helpers.getObjectWithSelectedKeys)(this.seedersList, selectedSeeders.map(function (name) {
          return (0, _helpers.normalizeSeederName)(name);
        }));
      }

      return this.seedersList;
    }
  }]);

  return MdSeedRunner;
}();

exports["default"] = MdSeedRunner;

_defineProperty(MdSeedRunner, "operations", {
  START: 'START',
  SUCCESS: 'SUCCESS',
  ERROR: 'ERROR',
  MONGOOSE_CONNECT_START: 'MONGOOSE_CONNECT_START',
  MONGOOSE_CONNECT_SUCCESS: 'MONGOOSE_CONNECT_SUCCESS',
  MONGOOSE_CONNECT_ERROR: 'MONGOOSE_CONNECT_ERROR',
  MONGOOSE_DROP_START: 'MONGOOSE_DROP_START',
  MONGOOSE_DROP_SUCCESS: 'MONGOOSE_DROP_SUCCESS',
  MONGOOSE_DROP_ERROR: 'MONGOOSE_DROP_ERROR',
  ALL_SEEDERS_START: 'ALL_SEEDERS_START',
  ALL_SEEDERS_FINISH: 'ALL_SEEDERS_FINISH',
  SEEDER_START: 'SEEDER_START',
  SEEDER_SUCCESS: 'SEEDER_SUCCESS',
  SEEDER_ERROR: 'SEEDER_ERROR'
});