Liferay.Loader.define("frontend-js-web@4.0.39/liferay/portlet/PortletInit.es", ['module', 'exports', 'require', 'frontend-js-metal-web$metal', 'frontend-js-web$uuid/v1', './../util/fetch.es', './RenderState.es', './portlet_constants.es', './portlet_util.es'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.default = exports.PortletInit = void 0;

    var _metal = require("frontend-js-metal-web$metal");

    var _v = _interopRequireDefault(require("frontend-js-web$uuid/v1"));

    var _fetch = _interopRequireDefault(require("./../util/fetch.es"));

    var _RenderState = _interopRequireDefault(require("./RenderState.es"));

    var _portlet_constants = _interopRequireDefault(require("./portlet_constants.es"));

    var _portlet_util = require("./portlet_util.es");

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

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

    function _toConsumableArray(arr) {
      return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
    }

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

    function _iterableToArray(iter) {
      if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
    }

    function _arrayWithoutHoles(arr) {
      if (Array.isArray(arr)) {
        for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
          arr2[i] = arr[i];
        }return arr2;
      }
    }

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

    /**
     * Flag specifying whether history is to be processed
     * (true if browser supports HTML5 session history APIs)
     * @type {boolean}
     * @review
     */
    var doHistory = window.history && window.history.pushState;
    /**
     * Regex for portlet-level events
     * @type {string}
     * @review
     */

    var portletRegex = '^portlet[.].*';
    /**
     * Determines if blocking action is currently in process.
     * @type {boolean}
     * @review
     */

    var busy = false;
    /**
     * An array containing the event listeners.
     * @type {Array.<Object>}
     * @review
     */

    var eventListeners = {};
    /**
     * An array containing the event listeners currently queued for being dispatched.
     * @type {Array.<Object>}
     * @review
     */

    var eventListenersQueue = [];
    /**
     * The page render state containing the all portlets and public parameters map.
     * @type {Object}
     * @review
     */

    var pageRenderState;
    /**
     * PortletInit
     * @review
     */

    var PortletInit = /*#__PURE__*/function () {
      function PortletInit(portletId) {
        _classCallCheck(this, PortletInit);

        this._portletId = portletId;
        this.constants = _objectSpread({}, _portlet_constants.default);

        if (!pageRenderState) {
          pageRenderState = global.portlet.data.pageRenderState;

          this._updateHistory(true);
        }

        this.portletModes = pageRenderState.portlets[this._portletId].allowedPM.slice(0);
        this.windowStates = pageRenderState.portlets[this._portletId].allowedWS.slice(0);
      }
      /**
       * Performs the actual action.
       * @param {Object} parameters Additional parameters to be set.
       * @param {HTMLFormElement} element Form to be submitted. May be <code>null</code>.
       * @protected
       * @review
       */

      _createClass(PortletInit, [{
        key: "_executeAction",
        value: function _executeAction(parameters, element) {
          var _this = this;

          return new Promise(function (resolve, reject) {
            (0, _portlet_util.getUrl)(pageRenderState, 'ACTION', _this._portletId, parameters).then(function (url) {
              var options = (0, _portlet_util.generateActionUrl)(_this._portletId, url, element);
              (0, _fetch.default)(options.url, options).then(function (res) {
                return res.text();
              }).then(function (text) {
                var updatedIds = _this._updatePageStateFromString(text, _this._portletId);

                resolve(updatedIds);
              }).catch(function (err) {
                reject(err);
              });
            });
          });
        }
        /**
         * Returns true if an onStateChange listener is registered for the portlet.
         * @memberof PortletInit
         * @param {string} portletId The portlet ID.
         * @return {boolean} Returns true if a listener is registered.
         * @protected
         * @review
         */

      }, {
        key: "_hasListener",
        value: function _hasListener(portletId) {
          var eventListenerPortletIds = Object.keys(eventListeners).map(function (key) {
            return eventListeners[key].id;
          });
          return eventListenerPortletIds.includes(portletId);
        }
        /**
         * Sends an onError event to all registered error event handlers for a given
         * portlet.
         * @memberof PortletInit
         * @param {string} portletId The portlet ID.
         * @param {string} err The error message.
         * @protected
         * @review
         */

      }, {
        key: "_reportError",
        value: function _reportError(portletId, err) {
          Object.keys(eventListeners).map(function (key) {
            var listener = eventListeners[key];

            if (listener.id === portletId && listener.type === 'portlet.onError') {
              setTimeout(function () {
                listener.handler('portlet.onError', err);
              });
            }

            return false;
          });
        }
        /**
         * Callback function that must be called after a partial action has been
         * started.
         *
         * The page state is generated by the portal and transmitted to the client by
         * the portlet. The portlet client that initiated the partial action must
         * pass the page state string to this function.
         *
         * The callback should only be called once to conclude a partial action sequence.
         * @memberof PortletInit
         * @param {string} portletId The portlet ID.
         * @param {string} updateString The new page state in string form.
         * @throws {TypeError} Thrown if the parameter is not a string.
         * @protected
         * @review
         */

      }, {
        key: "_setPageState",
        value: function _setPageState(portletId, updateString) {
          var _this2 = this;

          if (!(0, _metal.isString)(updateString)) {
            throw new TypeError("Invalid update string: ".concat(updateString));
          }

          this._updatePageState(updateString, portletId).then(function (updatedIds) {
            _this2._updatePortletStates(updatedIds);
          }, function (err) {
            busy = false;

            _this2._reportError(portletId, err);
          });
        }
        /**
         * Sets state for the portlet.
         * returns array of IDs for portlets that were affected by the change,
         * taking into account the public render parameters.
         * @memberof PortletInit
         * @param {Object} state The state to be set.
         * @return {Array}
         * @protected
         * @review
         */

      }, {
        key: "_setState",
        value: function _setState(state) {
          var _this3 = this;

          var publicRenderParameters = (0, _portlet_util.getUpdatedPublicRenderParameters)(pageRenderState, this._portletId, state);
          var updatedIds = [];
          var parameterKeys = Object.keys(publicRenderParameters);
          parameterKeys.forEach(function (parameterKey) {
            var newValue = publicRenderParameters[parameterKey];
            var groupMap = pageRenderState.prpMap[parameterKey];
            var groupKeys = Object.keys(groupMap);
            groupKeys.forEach(function (groupKey) {
              if (groupKey !== _this3._portletId) {
                var parts = groupMap[groupKey].split('|');
                var _portletId = parts[0];
                var parameterName = parts[1];

                if (newValue === undefined) {
                  delete pageRenderState.portlets[_portletId].state.parameters[parameterName];
                } else {
                  pageRenderState.portlets[_portletId].state.parameters[parameterName] = _toConsumableArray(newValue);
                }

                updatedIds.push(_portletId);
              }
            });
          });
          var portletId = this._portletId; // Update state for the initiating portlet.

          pageRenderState.portlets[portletId].state = state;
          updatedIds.push(portletId); // Delete render data for all affected portlets in order to avoid dispatching
          // stale render data

          updatedIds.forEach(function (updatedId) {
            pageRenderState.portlets[updatedId].renderData.content = null;
          }); // Update history for back-button support

          this._updateHistory();

          return Promise.resolve(updatedIds);
        }
        /**
         * Sets up for the action.
         * @memberof PortletInit
         * @param {Object} parameters Additional parameters. May be <code>null</code>.
         * @param {HTMLFormElement} element Form to be submitted May be <code>null</code>.
         * @throws {AccessDeniedException} Thrown if a blocking operation is already in progress.
         * @throws {NotInitializedException} Thrown if a portlet ID is provided, but no onStateChange
         * listener has been registered.
         * @protected
         * @review
         */

      }, {
        key: "_setupAction",
        value: function _setupAction(parameters, element) {
          var _this4 = this;

          if (this.isInProgress()) {
            throw {
              message: 'Operation is already in progress',
              name: 'AccessDeniedException'
            };
          }

          if (!this._hasListener(this._portletId)) {
            throw {
              message: "No onStateChange listener registered for portlet: ".concat(this._portletId),
              name: 'NotInitializedException'
            };
          }

          busy = true;
          return this._executeAction(parameters, element).then(function (updatedIds) {
            return _this4._updatePortletStates(updatedIds).then(function (updatedIds) {
              busy = false;
              return updatedIds;
            });
          }, function (err) {
            busy = false;

            _this4._reportError(_this4._portletId, err);
          });
        }
        /**
         * Called when the page state has been updated to allow
         * the browser history to be taken care of.
         * @memberof PortletInit
         * @param {boolean} replace Replace the state rather than pushing.
         * @protected
         * @review
         */

      }, {
        key: "_updateHistory",
        value: function _updateHistory(replace) {
          if (doHistory) {
            (0, _portlet_util.getUrl)(pageRenderState, 'RENDER', null, {}).then(function (url) {
              var token = JSON.stringify(pageRenderState);

              if (replace) {
                history.replaceState(token, '');
              } else {
                try {
                  history.pushState(token, '', url);
                } catch (e) {// Do nothing
                }
              }
            });
          }
        }
        /**
         * Update page state passed in after partial action. The list of
         * ID's of updated portlets is passed back through a promise in order
         * to decouple the layers.
         *
         * @memberof PortletInit
         * @param {string} updateString The updated render state string.
         * @review
         */

      }, {
        key: "_updatePageState",
        value: function _updatePageState(updateString) {
          var _this5 = this;

          return new Promise(function (resolve, reject) {
            try {
              var updatedIds = _this5._updatePageStateFromString(updateString, _this5._portletId);

              resolve(updatedIds);
            } catch (e) {
              reject(new Error("Partial Action decode status: ".concat(e.message)));
            }
          });
        }
        /**
         * Updates page state from string and returns array of portlet IDs
         * to be updated.
         *
         * @memberof PortletInit
         * @param {string} updateString The update string.
         * @param {string} portletId The portlet ID.
         * @protected
         * @review
         */

      }, {
        key: "_updatePageStateFromString",
        value: function _updatePageStateFromString(updateString, portletId) {
          var portlets = (0, _portlet_util.decodeUpdateString)(pageRenderState, updateString);
          var updatedIds = [];
          var stateUpdated = false; // Update portlets and collect IDs of affected portlets.

          var entries = Object.entries(portlets);
          entries.forEach(function (_ref) {
            var _ref2 = _slicedToArray(_ref, 2),
                key = _ref2[0],
                portletData = _ref2[1];

            pageRenderState.portlets[key] = portletData;
            updatedIds.push(key);
            stateUpdated = true;
          }); // portletId will be null or undefined when called from onpopstate routine.
          // In that case, don't update history.

          if (stateUpdated && portletId) {
            this._updateHistory();
          }

          return updatedIds;
        }
        /**
         *
         * Accepts an object containing changed render states.
         * Updates the state for each portlet present.
         *
         * @memberof PortletInit
         * @param {Array} updatedIds Array of portlet IDs to be updated.
         * @return {Promsise.<string>}
         * @protected
         * @review
         */

      }, {
        key: "_updatePortletStates",
        value: function _updatePortletStates(updatedIds) {
          var _this6 = this;

          return new Promise(function (resolve) {
            if (updatedIds.length === 0) {
              busy = false;
            } else {
              updatedIds.forEach(function (updatedId) {
                _this6._updateStateForPortlet(updatedId);
              });
            }

            resolve(updatedIds);
          });
        }
        /**
         * Updates the page render state
         *
         * @memberof PortletInit
         * @param {Object} state The new state to be set.
         * @protected
         * @review
         */

      }, {
        key: "_updateState",
        value: function _updateState(state) {
          var _this7 = this;

          if (busy) {
            throw {
              message: 'Operation in progress',
              name: 'AccessDeniedException'
            };
          } else if (!this._hasListener(this._portletId)) {
            throw {
              message: "No onStateChange listener registered for portlet: ".concat(this._portletId),
              name: 'NotInitializedException'
            };
          }

          busy = true;

          this._setState(state).then(function (updatedIds) {
            _this7._updatePortletStates(updatedIds);
          }).catch(function (err) {
            busy = false;

            _this7._reportError(_this7._portletId, err);
          });
        }
        /**
         * Calls the portlet onStateChange method in an asynchronous manner in order
         * to decouple the public API. This method is intended for use after
         * portlet client registers an onStateChange listener.
         *
         * @memberof PortletInit
         * @param {string} portletId The portlet ID.
         * @protected
         * @review
         */

      }, {
        key: "_updateStateForPortlet",
        value: function _updateStateForPortlet(portletId) {
          var updateQueueIds = eventListenersQueue.map(function (item) {
            return item.handle;
          });
          var entries = Object.entries(eventListeners);
          entries.forEach(function (_ref3) {
            var _ref4 = _slicedToArray(_ref3, 2),
                key = _ref4[0],
                eventData = _ref4[1];

            if (eventData.type !== 'portlet.onStateChange') {
              return;
            }

            if (eventData.id === portletId && !updateQueueIds.includes(key)) {
              eventListenersQueue.push(eventData);
            }
          });

          if (eventListenersQueue.length > 0) {
            setTimeout(function () {
              busy = true;

              while (eventListenersQueue.length > 0) {
                var eventData = eventListenersQueue.shift();
                var handler = eventData.handler;
                var id = eventData.id;

                if (!pageRenderState.portlets[id]) {
                  continue;
                }

                var renderData = pageRenderState.portlets[id].renderData;
                var renderState = new _RenderState.default(pageRenderState.portlets[id].state);

                if (renderData && renderData.content) {
                  handler('portlet.onStateChange', renderState, renderData);
                } else {
                  handler('portlet.onStateChange', renderState);
                }
              }

              busy = false;
            });
          }
        }
        /**
         * Initiates a portlet action using the specified action parameters and
         * element arguments.
         *
         * @memberof PortletInit
         * @param {PortletParameters} parameters Action parameters to be added to the URL
         * @param {HTMLFormElement} element DOM element of form to be submitted
         * @return {Promise} A Promise object that is resolved with no argument when the action request has completed.
         * @throws {TypeError} Thrown if the input parameters are invalid
         * @throws {AccessDeniedException} Thrown if a blocking operation is already in progress.
         * @throws {NotInitializedException} Thrown if a portlet ID is provided, but no onStateChange listener has been registered.
         * @review
         */

      }, {
        key: "action",
        value: function action() {
          var actionParameters = null;
          var argCount = 0;
          var el = null;

          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }

          args.forEach(function (arg) {
            if (arg instanceof HTMLFormElement) {
              if (el !== null) {
                throw new TypeError("Too many [object HTMLFormElement] arguments: ".concat(arg, ", ").concat(el));
              }

              el = arg;
            } else if ((0, _metal.isObject)(arg)) {
              (0, _portlet_util.validateParameters)(arg);

              if (actionParameters !== null) {
                throw new TypeError('Too many parameters arguments');
              }

              actionParameters = arg;
            } else if (arg !== undefined) {
              var type = Object.prototype.toString.call(arg);
              throw new TypeError("Invalid argument type. Argument ".concat(argCount + 1, " is of type ").concat(type));
            }

            argCount++;
          });

          if (el) {
            (0, _portlet_util.validateForm)(el);
          }

          return this._setupAction(actionParameters, el).then(function (val) {
            Promise.resolve(val);
          }).catch(function (err) {
            Promise.reject(err);
          });
        }
        /**
         * Adds a listener function for specified event type.
         *
         * @memberof PortletInit
         * @param {string} type The type of listener
         * @param {function} handler Function called when event occurs
         * @return {Object} A handle that can be used to remove the event listener
         * @throws {TypeError} Thrown if the input parameters are invalid
         * @review
         */

      }, {
        key: "addEventListener",
        value: function addEventListener(type, handler) {
          if (arguments.length > 2) {
            throw new TypeError('Too many arguments passed to addEventListener');
          }

          if (!(0, _metal.isString)(type) || !(0, _metal.isFunction)(handler)) {
            throw new TypeError('Invalid arguments passed to addEventListener');
          }

          var id = this._portletId;

          if (type.startsWith('portlet.')) {
            if (type !== 'portlet.onStateChange' && type !== 'portlet.onError') {
              throw new TypeError("The system event type is invalid: ".concat(type));
            }
          }

          var handle = (0, _v.default)();

          eventListeners[handle] = {
            handle: handle,
            handler: handler,
            id: id,
            type: type
          };

          if (type === 'portlet.onStateChange') {
            this._updateStateForPortlet(this._portletId);
          }

          return handle;
        }
        /**
         * Returns a promise for a resource URL with parameters set appropriately
         * for the page state according to the resource parameters, cacheability
         * option, and resource ID provided.
         * @memberof PortletInit
         * @param {Object} parameters Resource parameters to be added to the URL
         * @param {string} cache Cacheability option. The strings defined under
         * {@link PortletConstants} should be used to specifiy cacheability.
         * @param {string} resourceId Resource ID.
         * @return {Promise} A Promise object. Returns a string representing the
         * resource URL on successful resolution. Returns an Error object containing
         * a descriptive message on failure.
         * @throws {TypeError} Thrown if the input parameters are invalid
         * @review
         */

      }, {
        key: "createResourceUrl",
        value: function createResourceUrl(parameters, cache, resourceId) {
          if (arguments.length > 3) {
            throw new TypeError('Too many arguments. 3 arguments are allowed.');
          }

          if (parameters) {
            if ((0, _metal.isObject)(parameters)) {
              (0, _portlet_util.validateParameters)(parameters);
            } else {
              throw new TypeError('Invalid argument type. Resource parameters must be a parameters object.');
            }
          }

          var cacheability = null;

          if (cache) {
            if ((0, _metal.isString)(cache)) {
              if (cache === 'cacheLevelPage' || cache === 'cacheLevelPortlet' || cache === 'cacheLevelFull') {
                cacheability = cache;
              } else {
                throw new TypeError("Invalid cacheability argument: ".concat(cache));
              }
            } else {
              throw new TypeError('Invalid argument type. Cacheability argument must be a string.');
            }
          }

          if (!cacheability) {
            cacheability = 'cacheLevelPage';
          }

          if (resourceId && !(0, _metal.isString)(resourceId)) {
            throw new TypeError('Invalid argument type. Resource ID argument must be a string.');
          }

          return (0, _portlet_util.getUrl)(pageRenderState, 'RESOURCE', this._portletId, parameters, cacheability, resourceId);
        }
        /**
         * Dispatches a client event.
         * @memberof PortletInit
         * @param {string} type The type of listener.
         * @param {any} payload The payload to be delivered.
         * @return {number} The number of events queued for delivery.
         * @throws {TypeError} Thrown if the type is a system event type.
         * @review
         */

      }, {
        key: "dispatchClientEvent",
        value: function dispatchClientEvent(type, payload) {
          (0, _portlet_util.validateArguments)(arguments, 2, 2, ['string']);

          if (type.match(new RegExp(portletRegex))) {
            throw new TypeError('The event type is invalid: ' + type);
          }

          return Object.keys(eventListeners).reduce(function (amount, key) {
            var listener = eventListeners[key];

            if (type.match(listener.type)) {
              listener.handler(type, payload);
              amount++;
            }

            return amount;
          }, 0);
        }
        /**
         * Tests whether a blocking operation is in progress.
         * @memberof PortletInit
         * @return {boolean}
         * @review
         */

      }, {
        key: "isInProgress",
        value: function isInProgress() {
          return busy;
        }
        /**
         * Creates and returns a new PortletParameters object.
         * @memberof PortletInit
         * @param {?Object} optParameters The optional parameters to be copied.
         * @return {Object} The new parameters object.
         * @review
         */

      }, {
        key: "newParameters",
        value: function newParameters() {
          var optParameters = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
          var newParameters = {};
          Object.keys(optParameters).forEach(function (key) {
            if (Array.isArray(optParameters[key])) {
              newParameters[key] = _toConsumableArray(optParameters[key]);
            }
          });
          return newParameters;
        }
        /**
         * Creates and returns a new RenderState object.
         * @memberof PortletInit
         * @param {?RenderState} optState An optional RenderState object to be copied.
         * @return {RenderState} The new RenderState object.
         * @review
         */

      }, {
        key: "newState",
        value: function newState(optState) {
          return new _RenderState.default(optState);
        }
        /**
         * Removes a previously added listener function designated by the handle.
         * The handle must be the same object previously returned by the
         * addEventListener function.
         * @memberof PortletInit
         * @param {Object} handle The handle of the listener to be removed.
         * @throws {TypeError} Thrown if the input parameters are invalid.
         * @throws {AccessDeniedException} Thrown if the event listener associated
         * with this handle was registered by a different portlet.
         * @review
         */

      }, {
        key: "removeEventListener",
        value: function removeEventListener(handle) {
          if (arguments.length > 1) {
            throw new TypeError('Too many arguments passed to removeEventListener');
          }

          if (!(0, _metal.isDefAndNotNull)(handle)) {
            throw new TypeError("The event handle provided is ".concat(_typeof(handle)));
          }

          var found = false;

          if ((0, _metal.isObject)(eventListeners[handle])) {
            if (eventListeners[handle].id === this._portletId) {
              delete eventListeners[handle];
              var l = eventListenersQueue.length;

              for (var i = 0; i < l; i++) {
                var eventData = eventListenersQueue[i];

                if (eventData && eventData.handle === handle) {
                  eventListenersQueue.splice(i, 1);
                }
              }

              found = true;
            }
          }

          if (!found) {
            throw new TypeError("The event listener handle doesn't match any listeners.");
          }
        }
        /**
         * Sets the render state, which consists of the public and private render
         * parameters, the portlet mode, and the window state.
         * @memberof PortletInit
         * @param {RenderState} state The new state to be set.
         * @throws {TypeError} Thrown if the input parameters are invalid.
         * @throws {AccessDeniedException} Thrown if a blocking operation is already in progress.
         * @throws {NotInitializedException} Thrown if a portlet ID is provided, but no onStateChange
         * listener has been registered.
         * @review
         */

      }, {
        key: "setRenderState",
        value: function setRenderState(state) {
          (0, _portlet_util.validateArguments)(arguments, 1, 1, ['object']);

          if (pageRenderState.portlets && pageRenderState.portlets[this._portletId]) {
            var portletData = pageRenderState.portlets[this._portletId];
            (0, _portlet_util.validateState)(state, portletData);

            this._updateState(state);
          }
        }
        /**
         * Starts partial action processing and returns a {@link PartialActionInit} object to the caller.
         * @memberof PortletInit
         * @param {PortletParameters} actionParameters Action parameters to be added to the URL.
         * @return {Promise} A Promise. Returns a {@link PortletActionInit} object
         * containing a partial action URL and the _setPageState callback function
         * on successful resolution. Returns an Error object containing a
         * descriptive message on failure.
         * @throws {TypeError} Thrown if the input parameters are invalid.
         * @throws {AccessDeniedException} Thrown if a blocking operation is already in progress.
         * @throws {NotInitializedException} Thrown if a portlet ID is provided, but
         * no onStateChange listener has been registered.
         * @review
         */

      }, {
        key: "startPartialAction",
        value: function startPartialAction(actionParameters) {
          var instance = this;
          var parameters = null;

          if (arguments.length > 1) {
            throw new TypeError('Too many arguments. 1 arguments are allowed');
          } else if (actionParameters !== undefined) {
            if ((0, _metal.isObject)(actionParameters)) {
              (0, _portlet_util.validateParameters)(actionParameters);
              parameters = actionParameters;
            } else {
              throw new TypeError("Invalid argument type. Argument is of type ".concat(_typeof(actionParameters)));
            }
          }

          if (busy === true) {
            throw {
              message: 'Operation in progress',
              name: 'AccessDeniedException'
            };
          } else if (!this._hasListener(this._portletId)) {
            throw {
              message: "No onStateChange listener registered for portlet: ".concat(this._portletId),
              name: 'NotInitializedException'
            };
          }

          busy = true;
          var partialActionInitObject = {
            setPageState: function setPageState(updateString) {
              instance._setPageState(instance._portletId, updateString);
            },
            url: ''
          };
          return (0, _portlet_util.getUrl)(pageRenderState, 'PARTIAL_ACTION', this._portletId, parameters).then(function (url) {
            partialActionInitObject.url = url;
            return partialActionInitObject;
          });
        }
      }]);

      return PortletInit;
    }();

    exports.PortletInit = PortletInit;
    var _default = PortletInit;
    exports.default = _default;
    //# sourceMappingURL=PortletInit.es.js.map
  }
});
//# sourceMappingURL=PortletInit.es.js.map