"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

require("core-js/modules/es.reflect.construct.js");

require("core-js/modules/es.object.create.js");

require("core-js/modules/es.object.define-property.js");

require("core-js/modules/es.array.slice.js");

require("core-js/modules/es.array.from.js");

require("core-js/modules/es.symbol.js");

require("core-js/modules/es.symbol.description.js");

require("core-js/modules/es.symbol.iterator.js");

require("core-js/modules/es.object.keys.js");

require("core-js/modules/es.array.index-of.js");

require("core-js/modules/es.array.filter.js");

require("core-js/modules/es.object.get-own-property-descriptor.js");

require("core-js/modules/es.array.for-each.js");

require("core-js/modules/web.dom-collections.for-each.js");

require("core-js/modules/es.object.get-own-property-descriptors.js");

require("core-js/modules/es.object.define-properties.js");

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

require("regenerator-runtime/runtime.js");

require("core-js/modules/es.array.concat.js");

require("core-js/modules/es.array.is-array.js");

require("core-js/modules/es.function.name.js");

require("core-js/modules/es.array.map.js");

require("core-js/modules/es.array.iterator.js");

require("core-js/modules/es.object.to-string.js");

require("core-js/modules/es.promise.js");

require("core-js/modules/es.string.iterator.js");

require("core-js/modules/web.dom-collections.iterator.js");

require("core-js/modules/es.array.flat.js");

require("core-js/modules/es.object.set-prototype-of.js");

require("core-js/modules/es.object.get-prototype-of.js");

var _baseResourceWithId = require("./base-resource-with-id");

var _errors = require("./errors");

var _functions = require("./functions");

var _server = require("./server");

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

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

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

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 _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

/**
 * Base class for all API resources.
 * In case of error in:
 *  - list
 *  - get
 *  - save
 *  - delete
 *
 * methods, throws an APIResponseError with the result of
 * calling handleError on the response received from server.
 */
var Resource = /*#__PURE__*/function (_BaseResourceWithId) {
  _inherits(Resource, _BaseResourceWithId);

  var _super = _createSuper(Resource);

  function Resource() {
    _classCallCheck(this, Resource);

    return _super.apply(this, arguments);
  }

  _createClass(Resource, [{
    key: "save",
    value:
    /**
     * Create or update this resource on the server
     * In case of error, it throws an APIResponseError which
     * contains the result of calling handleError(errorResponse)
     */
    function () {
      var _save = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(timeout) {
        var server, payload, cls, response, method;
        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                server = new _server.APIServer({
                  timeout: timeout
                });
                payload = this.serializeAPI();
                cls = this.constructor;
                method = this.id ? "UPDATE" : "CREATE";

                if (this.id) {
                  _context.next = 10;
                  break;
                }

                _context.next = 7;
                return server.post(cls.path, undefined, payload);

              case 7:
                response = _context.sent;
                _context.next = 13;
                break;

              case 10:
                _context.next = 12;
                return server.put(cls.path, this.id, undefined, payload);

              case 12:
                response = _context.sent;

              case 13:
                if (!response.error) {
                  _context.next = 17;
                  break;
                }

                throw new _errors.APIResponseError("".concat(method, " error in ").concat(cls.resourceName), cls.handleError(response));

              case 17:
                this.deserializeAPI(response.data); // If it's saved correctly, it's not dirty anymore

                this._dirty = false;

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

      function save(_x) {
        return _save.apply(this, arguments);
      }

      return save;
    }()
    /**
     * Delete the resource on the server.
     * In case of error, it throws an APIResponseError which
     * contains the result of calling handleError(errorResponse)
     */

  }, {
    key: "delete",
    value: function () {
      var _delete2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
        var cls, server, response;
        return regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                cls = this.constructor;

                if (this.id) {
                  _context2.next = 3;
                  break;
                }

                throw new _errors.DeleteError(cls.resourceName);

              case 3:
                server = new _server.APIServer();
                _context2.next = 6;
                return server["delete"](cls.path, this.id);

              case 6:
                response = _context2.sent;

                if (!response.error) {
                  _context2.next = 11;
                  break;
                }

                throw new _errors.APIResponseError("DESTROY error in ".concat(cls.resourceName), cls.handleError(response));

              case 11:
                this._dirty = false;
                this._id = undefined;

              case 13:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }));

      function _delete() {
        return _delete2.apply(this, arguments);
      }

      return _delete;
    }()
    /**
     * Parse a response from the list endpoint from the API server.
     *
     * @param data Data from the server
     *
     * @returns The list of data from the api server.
     */

  }], [{
    key: "apiFactory",
    value:
    /**
     * Provide an implementation for creating the resource from API server data.
     *
     * @param data The data from the server
     *
     * @returns A new resource created from the given data.
     */
    function apiFactory( // @ts-ignore
    data) {
      throw new _errors.NotImplementedError();
    }
    /**
     * Provide an implementation for creating the resource from the Redux store.
     *
     * @param data The data from the Redux store
     *
     * @returns A new resource created from the given data.
     */

  }, {
    key: "reduxFactory",
    value: function reduxFactory( // eslint-disable-next-line
    // @ts-ignore
    data) {
      throw new _errors.NotImplementedError();
    }
    /**
     * Fetch the resource from the server.
     * In case of error, it throws an APIResponseError which
     * contains the result of calling handleError(errorResponse)
     *
     * @param id The id of the resource.
     * @param queryParams Params to send with the request.
     *
     * @returns The resource.
     */

  }, {
    key: "get",
    value: function () {
      var _get = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(id, queryParams) {
        var server, response;
        return regeneratorRuntime.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                server = new _server.APIServer();
                _context3.next = 3;
                return server.get(this.path, id, queryParams);

              case 3:
                response = _context3.sent;

                if (!response.error) {
                  _context3.next = 6;
                  break;
                }

                throw new _errors.APIResponseError("RETRIEVE error in ".concat(this.resourceName), this.handleError(response));

              case 6:
                if (!Array.isArray(response.data)) {
                  _context3.next = 8;
                  break;
                }

                throw new _errors.MultipleObjectsReturnedError(this.resourceName);

              case 8:
                return _context3.abrupt("return", this.apiFactory(response.data));

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

      function get(_x2, _x3) {
        return _get.apply(this, arguments);
      }

      return get;
    }()
    /**
     * List the resource.
     * In case of error, it throws an APIResponseError which
     * contains the result of calling handleError(errorResponse)
     * @param queryParams Params to send with the request.
     * @param cancelToken Token that allows to cancel pending request.
     * @param timeout Timeout value for the request.
     * @returns The list of resources from the server.
     */

  }, {
    key: "list",
    value: function () {
      var _list = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(queryParams) {
        var _ref,
            cancelToken,
            timeout,
            server,
            response,
            result,
            dataList,
            _iterator,
            _step,
            resourceData,
            resource,
            _args4 = arguments;

        return regeneratorRuntime.wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                _ref = _args4.length > 1 && _args4[1] !== undefined ? _args4[1] : {}, cancelToken = _ref.cancelToken, timeout = _ref.timeout;
                server = new _server.APIServer({
                  timeout: timeout
                });
                _context4.next = 4;
                return server.get(this.path, undefined, queryParams, {
                  cancelToken: cancelToken
                });

              case 4:
                response = _context4.sent;

                if (!response.error) {
                  _context4.next = 7;
                  break;
                }

                throw new _errors.APIResponseError("LIST error in ".concat(this.resourceName), this.handleError(response));

              case 7:
                result = [];
                dataList = this.parseList(response.data);
                _iterator = _createForOfIteratorHelper(dataList);

                try {
                  for (_iterator.s(); !(_step = _iterator.n()).done;) {
                    resourceData = _step.value;
                    resource = this.apiFactory(resourceData);
                    result.push(resource);
                  }
                } catch (err) {
                  _iterator.e(err);
                } finally {
                  _iterator.f();
                }

                return _context4.abrupt("return", result);

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

      function list(_x4) {
        return _list.apply(this, arguments);
      }

      return list;
    }()
  }, {
    key: "parseList",
    value: function parseList(data) {
      var _this$resourceName;

      if (Array.isArray(data)) {
        return data;
      } else if (data !== null && data !== void 0 && data.results && Array.isArray(data.results)) {
        return data.results;
      }

      throw new _errors.NotAListError((_this$resourceName = this === null || this === void 0 ? void 0 : this.resourceName) !== null && _this$resourceName !== void 0 ? _this$resourceName : this === null || this === void 0 ? void 0 : this.name);
    }
    /**
     * List paginated resource.
     * In case of error, it throws an APIResponseError which
     * contains the result of calling handleError(errorResponse)
     * @param queryParams Params to send with the request.
     * @param cancelToken Token that allows to cancel pending request.
     * @param timeout Timeout value for the request.
     * @returns {PaginatedResponse}
     */

  }, {
    key: "paginatedList",
    value: function () {
      var _paginatedList = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5(queryParams) {
        var _this = this;

        var _ref2,
            cancelToken,
            timeout,
            server,
            response,
            _ref3,
            results,
            count,
            next,
            previous,
            resultResources,
            _args5 = arguments;

        return regeneratorRuntime.wrap(function _callee5$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                _ref2 = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : {}, cancelToken = _ref2.cancelToken, timeout = _ref2.timeout;
                server = new _server.APIServer({
                  timeout: timeout
                });
                _context5.next = 4;
                return server.get(this.path, undefined, queryParams, {
                  cancelToken: cancelToken
                });

              case 4:
                response = _context5.sent;

                if (!response.error) {
                  _context5.next = 7;
                  break;
                }

                throw new _errors.APIResponseError("Paginated LIST error in ".concat(this.resourceName), this.handleError(response));

              case 7:
                _ref3 = response.data, results = _ref3.results, count = _ref3.count, next = _ref3.next, previous = _ref3.previous;
                resultResources = results.map(function (result) {
                  return _this.apiFactory(result);
                });
                return _context5.abrupt("return", {
                  results: resultResources,
                  count: count,
                  next: next,
                  previous: previous
                });

              case 10:
              case "end":
                return _context5.stop();
            }
          }
        }, _callee5, this);
      }));

      function paginatedList(_x5) {
        return _paginatedList.apply(this, arguments);
      }

      return paginatedList;
    }()
    /**
     * Batch list resource.
     * In case of error, it throws an APIResponseError which
     * contains the result of calling handleError(errorResponse)
     * @param queryParams Params to send with the request.
     * @param cancelToken Token that allows to cancel pending request.
     * @param timeout Timeout value for the request.
     * @returns List of data from server
     */

  }, {
    key: "batchList",
    value: function () {
      var _batchList = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6(batchParamKey, queryParams) {
        var _this2 = this;

        var batchSize,
            _ref4,
            cancelToken,
            timeout,
            batchParam,
            otherParams,
            batches,
            processedBatches,
            _args6 = arguments;

        return regeneratorRuntime.wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                batchSize = _args6.length > 2 && _args6[2] !== undefined ? _args6[2] : 125;
                _ref4 = _args6.length > 3 && _args6[3] !== undefined ? _args6[3] : {}, cancelToken = _ref4.cancelToken, timeout = _ref4.timeout;

                if (queryParams.hasOwnProperty(batchParamKey)) {
                  _context6.next = 4;
                  break;
                }

                throw new Error("queryParams has no key ".concat(batchParamKey));

              case 4:
                batchParam = queryParams.batchParamKey, otherParams = _objectWithoutProperties(queryParams, ["batchParamKey"]);

                if (Array.isArray(batchParam)) {
                  _context6.next = 7;
                  break;
                }

                throw new Error("queryParams.".concat(batchParam, " must be an array"));

              case 7:
                batches = (0, _functions.chunk)(batchParam, batchSize);
                _context6.next = 10;
                return Promise.all(batches.map(function (batch) {
                  return _this2.list(_objectSpread({
                    batchParamKey: batch
                  }, otherParams), {
                    cancelToken: cancelToken,
                    timeout: timeout
                  });
                }));

              case 10:
                processedBatches = _context6.sent;
                return _context6.abrupt("return", processedBatches.flat().map(function (result) {
                  return _this2.apiFactory(result);
                }));

              case 12:
              case "end":
                return _context6.stop();
            }
          }
        }, _callee6);
      }));

      function batchList(_x6, _x7) {
        return _batchList.apply(this, arguments);
      }

      return batchList;
    }()
    /**
     * Bulk create resources on the server
     * In case of error, it throws an APIResponseError which
     * contains the result of calling handleError(errorResponse)
     */

  }, {
    key: "bulkCreate",
    value: function () {
      var _bulkCreate = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee7(instances) {
        var _ref5,
            timeout,
            server,
            payload,
            response,
            result,
            dataList,
            _iterator2,
            _step2,
            resourceData,
            resource,
            _args7 = arguments;

        return regeneratorRuntime.wrap(function _callee7$(_context7) {
          while (1) {
            switch (_context7.prev = _context7.next) {
              case 0:
                _ref5 = _args7.length > 1 && _args7[1] !== undefined ? _args7[1] : {}, timeout = _ref5.timeout;
                server = new _server.APIServer({
                  timeout: timeout
                });
                payload = instances.map(function (instance) {
                  return instance.serializeAPI();
                });
                _context7.next = 5;
                return server.post(this.path, undefined, payload);

              case 5:
                response = _context7.sent;

                if (!response.error) {
                  _context7.next = 10;
                  break;
                }

                throw new _errors.APIResponseError("Bulk create error in ".concat(this.resourceName), this.handleError(response));

              case 10:
                result = [];
                dataList = this.parseList(response.data);
                _iterator2 = _createForOfIteratorHelper(dataList);

                try {
                  for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
                    resourceData = _step2.value;
                    resource = this.apiFactory(resourceData);
                    result.push(resource);
                  }
                } catch (err) {
                  _iterator2.e(err);
                } finally {
                  _iterator2.f();
                }

                return _context7.abrupt("return", result);

              case 15:
              case "end":
                return _context7.stop();
            }
          }
        }, _callee7, this);
      }));

      function bulkCreate(_x8) {
        return _bulkCreate.apply(this, arguments);
      }

      return bulkCreate;
    }()
  }]);

  return Resource;
}(_baseResourceWithId.BaseResourceWithId);

exports.Resource = Resource;
//# sourceMappingURL=data:application/json;charset=utf-8;base64, 