Liferay.Loader.define("layout-content-page-editor-web@2.0.110/page_editor/app/services/serviceFetch", ['module', 'exports', 'require', 'frontend-js-web', '../actions/index', '../config/constants/serviceNetworkStatusTypes', '../config/index'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.default = serviceFetch;

    var _frontendJsWeb = require("frontend-js-web");

    var _index = require("../actions/index");

    var _serviceNetworkStatusTypes = require("../config/constants/serviceNetworkStatusTypes");

    var _index2 = require("../config/index");

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

    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 _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) {
      if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
        return;
      }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;
    }

    /**
     * Returns a new FormData built from the given object.
     * @param {object} body
     * @return {FormData}
     * @review
     */
    function getFormData(body) {
      var formData = new FormData();
      Object.entries(body).forEach(function (_ref) {
        var _ref2 = _slicedToArray(_ref, 2),
            key = _ref2[0],
            value = _ref2[1];

        formData.append("".concat(_index2.config.portletNamespace).concat(key), value);
      });
      return formData;
    }
    /**
     * Performs a POST request to the given url and parses an expected object response.
     * If the response status is over 400, or there is any "error" or "exception"
     * properties on the response object, it rejects the promise with an Error object.
     * @param {string} url
     * @param {object} [body={}]
     * @param {function} onNetworkStatus
     * @param {{ requestGenerateDraft: boolean }} [options={requestGenerateDraft: false}]
     * @private
     * @return {Promise<object>}
     * @review
     */

    function serviceFetch(url) {
      var _ref3 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
        body: {}
      };

      var onNetworkStatus = arguments.length > 2 ? arguments[2] : undefined;

      var _ref4 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {
        requestGenerateDraft: false
      },
          _ref4$requestGenerate = _ref4.requestGenerateDraft,
          requestGenerateDraft = _ref4$requestGenerate === void 0 ? false : _ref4$requestGenerate;

      var _ref3$body = _ref3.body,
          body = _ref3$body === void 0 ? {} : _ref3$body,
          method = _ref3.method,
          options = _objectWithoutProperties(_ref3, ["body", "method"]);

      if (requestGenerateDraft) {
        onNetworkStatus((0, _index.updateNetwork)({
          status: _serviceNetworkStatusTypes.SERVICE_NETWORK_STATUS_TYPES.savingDraft
        }));
      }

      return (0, _frontendJsWeb.fetch)(url, _objectSpread(_objectSpread({}, options), {}, {
        body: getFormData(body),
        method: method || 'POST'
      })).then(function (response) {
        return new Promise(function (resolve, reject) {
          response.clone().json().then(function (body) {
            return resolve([response, body]);
          }).catch(function () {
            return response.clone().text();
          }).then(function (body) {
            return resolve([response, body]);
          }).catch(reject);
        });
      }).then(function (_ref5) {
        var _ref6 = _slicedToArray(_ref5, 2),
            response = _ref6[0],
            body = _ref6[1];

        if (_typeof(body) === 'object') {
          if ('exception' in body) {
            return handleErroredResponse(Liferay.Language.get('an-unexpected-error-occurred'), onNetworkStatus);
          } else if ('error' in body) {
            return handleErroredResponse(Liferay.Language.get(body.error), onNetworkStatus);
          }
        } else {
          return handleErroredResponse(Liferay.Language.get('an-unexpected-error-occurred'), onNetworkStatus);
        }

        if (response.status >= 400) {
          return handleErroredResponse(Liferay.Language.get('an-unexpected-error-occurred'), onNetworkStatus);
        }

        if (requestGenerateDraft) {
          onNetworkStatus((0, _index.updateNetwork)({
            error: null,
            status: _serviceNetworkStatusTypes.SERVICE_NETWORK_STATUS_TYPES.draftSaved
          }));
        }

        return body;
      });
    }
    /**
     * @param {string} error
     * @param {function} onNetworkStatus
     */

    function handleErroredResponse(error, onNetworkStatus) {
      onNetworkStatus((0, _index.updateNetwork)({
        error: error,
        status: _serviceNetworkStatusTypes.SERVICE_NETWORK_STATUS_TYPES.error
      }));
      return Promise.reject(error);
    }
    //# sourceMappingURL=serviceFetch.js.map
  }
});
//# sourceMappingURL=serviceFetch.js.map