Liferay.Loader.define("commerce-cart-taglib@4.0.12/add_to_cart/AddToCart.es", ['module', 'exports', 'require', 'frontend-js-web', 'frontend-js-metal-web$metal-component', 'frontend-js-metal-web$metal-soy', 'frontend-js-metal-web$metal-state', './AddToCart.soy'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.default = void 0;

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

    var _metalComponent = _interopRequireDefault(require("frontend-js-metal-web$metal-component"));

    var _metalSoy = _interopRequireDefault(require("frontend-js-metal-web$metal-soy"));

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

    var _AddToCart = _interopRequireDefault(require("./AddToCart.soy"));

    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 _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 _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 _getPrototypeOf(o) {
      _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
        return o.__proto__ || Object.getPrototypeOf(o);
      };return _getPrototypeOf(o);
    }

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

    var AddToCart = /*#__PURE__*/function (_Component) {
      _inherits(AddToCart, _Component);

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

        return _possibleConstructorReturn(this, _getPrototypeOf(AddToCart).apply(this, arguments));
      }

      _createClass(AddToCart, [{
        key: "created",
        value: function created() {
          Liferay.on(this.cpDefinitionId + 'CPInstance:change', this._instanceChange.bind(this));
        }
        /**
         * Makes an ajax request to submit the data.
         * @param {Event} event
         * @protected
         */

      }, {
        key: "_addToCart",
        value: function _addToCart() {
          var instance = this;
          var _quantity = this.quantity;
          var ddmFormValues = [];

          var productContent = this._getProductContent();

          if (productContent) {
            ddmFormValues = JSON.stringify(productContent.getFormValues() || ddmFormValues);

            if (this.cpInstanceId == '0') {
              this.cpInstanceId = productContent.getCPInstanceId();
            }
          }

          var quantityNode = document.querySelector('#' + this.taglibQuantityInputId);

          if (quantityNode) {
            _quantity = quantityNode.value;
          }

          var formData = new FormData();
          formData.append(this.portletNamespace + 'cpDefinitionId', this.cpDefinitionId);
          formData.append(this.portletNamespace + 'cpInstanceId', this.cpInstanceId);
          formData.append(this.portletNamespace + 'ddmFormValues', ddmFormValues);
          formData.append(this.portletNamespace + 'quantity', _quantity);
          (0, _frontendJsWeb.fetch)(this.uri, {
            body: formData,
            method: 'POST'
          }).then(function (response) {
            return response.json();
          }).then(function (jsonresponse) {
            if (jsonresponse.success) {
              Liferay.fire('commerce:productAddedToCart', jsonresponse);

              instance._showNotification(jsonresponse.successMessage, 'success');
            } else {
              var validatorErrors = jsonresponse.validatorErrors;

              if (validatorErrors) {
                validatorErrors.forEach(function (validatorError) {
                  instance._showNotification(validatorError.message, 'danger');
                });
              } else {
                instance._showNotification(jsonresponse.error, 'danger');
              }
            }
          });
        }
      }, {
        key: "_getProductContent",
        value: function _getProductContent() {
          return Liferay.component(this.productContentId);
        }
      }, {
        key: "_handleClick",
        value: function _handleClick() {
          var instance = this;

          var productContent = this._getProductContent();

          if (productContent) {
            productContent.validateProduct(function (hasError) {
              if (!hasError) {
                instance._addToCart();
              }
            });
          } else {
            this._addToCart();
          }
        }
      }, {
        key: "_instanceChange",
        value: function _instanceChange(event) {
          if (event.cpInstanceExist) {
            this.cpInstanceId = event.cpInstanceId;
          }
        }
      }, {
        key: "_showNotification",
        value: function _showNotification(message, type) {
          AUI().use('liferay-notification', function () {
            new Liferay.Notification({
              closeable: true,
              delay: {
                hide: 5000,
                show: 0
              },
              duration: 500,
              message: message,
              render: true,
              title: '',
              type: type
            });
          });
        }
      }]);

      return AddToCart;
    }(_metalComponent.default);
    /**
     * State definition.
     * @ignore
     * @static
     * @type {!Object}
     */

    AddToCart.STATE = {
      /**
       * CPDefinitionId.
       * @instance
       * @memberof AddToCart
       * @type {?number}
       * @default undefined
       */
      cpDefinitionId: _metalState.Config.string(),

      /**
       * CPInstanceId.
       * @instance
       * @memberof AddToCart
       * @type {?number}
       * @default undefined
       */
      cpInstanceId: _metalState.Config.string(),

      /**
       * CSS classes to be applied to the element.
       * @instance
       * @memberof AddToCart
       * @type {?string}
       * @default undefined
       */
      elementClasses: _metalState.Config.string(),

      /**
       * Component id.
       * @instance
       * @memberof AddToCart
       * @type {String}
       */
      id: _metalState.Config.string().required(),

      /**
       * Text to display inside the add to cart button.
       * @instance
       * @memberof AddToCart
       * @type {String}
       */
      label: _metalState.Config.string().required(),

      /**
       * Portlet's namespace
       * @instance
       * @memberof AddToCart
       * @type {String}
       */
      portletNamespace: _metalState.Config.string().required(),

      /**
       * Product content id
       * @instance
       * @memberof AddToCart
       * @type {String}
       */
      productContentId: _metalState.Config.string(),

      /**
       * Default quantity to add to cart.
       * @instance
       * @memberof AddToCart
       * @type {?string}
       * @default undefined
       */
      quantity: _metalState.Config.string(),

      /**
       * Id of the html input to get the quantity.
       * @instance
       * @memberof AddToCart
       * @type {?string}
       * @default undefined
       */
      taglibQuantityInputId: _metalState.Config.string(),

      /**
       * Uri to add a cart item.
       * @instance
       * @memberof AddToCart
       * @type {String}
       */
      uri: _metalState.Config.string().required()
    }; // Register component

    _metalSoy.default.register(AddToCart, _AddToCart.default);

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