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

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

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

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

    var _AddToCartButton = _interopRequireDefault(require("./AddToCartButton.soy"));

    require("../quantity_selector/QuantitySelector.es");

    function _getRequireWildcardCache() {
      if (typeof WeakMap !== "function") return null;var cache = new WeakMap();_getRequireWildcardCache = function _getRequireWildcardCache() {
        return cache;
      };return cache;
    }

    function _interopRequireWildcard(obj) {
      if (obj && obj.__esModule) {
        return obj;
      }if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") {
        return { default: obj };
      }var cache = _getRequireWildcardCache();if (cache && cache.has(obj)) {
        return cache.get(obj);
      }var newObj = {};var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;for (var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;if (desc && (desc.get || desc.set)) {
            Object.defineProperty(newObj, key, desc);
          } else {
            newObj[key] = obj[key];
          }
        }
      }newObj.default = obj;if (cache) {
        cache.set(obj, newObj);
      }return newObj;
    }

    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 notificationDidShow = false;
    var ALL = 'all';

    function showNotification(message, type) {
      if (!notificationDidShow) {
        AUI().use('liferay-notification', function () {
          new Liferay.Notification({
            closeable: true,
            delay: {
              hide: 5000,
              show: 0
            },
            duration: 500,
            message: message,
            render: true,
            title: '',
            type: type
          });
        });
      }

      notificationDidShow = true;
      setTimeout(function () {
        notificationDidShow = false;
      }, 500);
    }

    function resetInputQuantity() {
      this.inputQuantity = this.settings.allowedQuantities && this.settings.allowedQuantities.length ? this.settings.allowedQuantities[0] : this.settings.minQuantity;
    }

    function doSubmit() {
      var _this = this;

      var formData = new FormData();
      formData.append('commerceAccountId', this.accountId);
      formData.append('groupId', themeDisplay.getScopeGroupId());
      formData.append('productId', this.productId);
      formData.append('languageId', themeDisplay.getLanguageId());
      formData.append('quantity', this.inputQuantity);
      formData.append('options', this.options);

      if (this.orderId) {
        formData.append('orderId', this.orderId);
      }

      return (0, _frontendJsWeb.fetch)(this.cartAPI, {
        body: formData,
        method: 'POST'
      }).then(function (response) {
        return response.json();
      }).then(function (jsonresponse) {
        if (jsonresponse.success) {
          if (jsonresponse.products) {
            Liferay.fire('refreshCartUsingData', {
              detailsUrl: jsonresponse.detailsUrl,
              orderId: jsonresponse.orderId,
              products: jsonresponse.products,
              summary: jsonresponse.summary,
              valid: jsonresponse.valid
            });
          }

          if (_this.orderId !== jsonresponse.orderId) {
            Liferay.fire('orderChanged', {
              orderId: jsonresponse.orderId
            });
            _this.orderId = jsonresponse.orderId;
          }

          _this._animateMarker(_this.quantity);

          _this.quantity = _this.inputQuantity;
          resetInputQuantity.call(_this);
          Liferay.fire('commerce:productAddedToCart', jsonresponse);
        } else if (jsonresponse.errorMessages) {
          showNotification(jsonresponse.errorMessages[0], 'danger');
        } else {
          var validatorErrors = jsonresponse.validatorErrors;

          if (validatorErrors) {
            validatorErrors.forEach(function (validatorError) {
              showNotification(validatorError.message, 'danger');
            });
          } else {
            showNotification(jsonresponse.error, 'danger');
          }
        }
      }).catch(function (_weShouldHandleErrors) {});
    }

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

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

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

      _createClass(AddToCartButton, [{
        key: "created",
        value: function created() {
          resetInputQuantity.call(this);
          this._handleMarkerAnimation = this._handleMarkerAnimation.bind(this);
        }
      }, {
        key: "_animateMarker",
        value: function _animateMarker(prevQuantity) {
          if (prevQuantity === 0) {
            this.updatingTransition = 'adding';
          } else {
            this.updatingTransition = 'incrementing';
          }

          this.refs.marker.addEventListener('animationend', this._handleMarkerAnimation, this);
        }
      }, {
        key: "_handleMarkerAnimation",
        value: function _handleMarkerAnimation() {
          this.updatingTransition = null;
          this.refs.marker.removeEventListener('animationend', this._handleMarkerAnimation, this);
        }
      }, {
        key: "attached",
        value: function attached() {
          window.Liferay.on('accountSelected', this._handleAccountChange, this);
          window.Liferay.on('productRemovedFromCart', this._handleCartProductRemoval, this); // TODO: event definition to be imported as a constant

          window.Liferay.on('current-product-status-changed', this._handleCurrentProductStatusChange, this);
        }
      }, {
        key: "detached",
        value: function detached() {
          window.Liferay.detach('accountSelected', this._handleAccountChange, this);
          window.Liferay.detach('productRemovedFromCart', this._handleCartProductRemoval, this); // TODO: event definition to be imported as a constant

          window.Liferay.detach('current-product-status-changed', this._handleCurrentProductStatusChange, this);
        }
      }, {
        key: "_handleUpdateQuantity",
        value: function _handleUpdateQuantity(quantity) {
          this.inputQuantity = quantity;
        }
      }, {
        key: "_handleSubmitQuantity",
        value: function _handleSubmitQuantity(quantity) {
          this._handleUpdateQuantity(quantity);

          this._handleSubmitClick();
        }
      }, {
        key: "_handleCurrentProductStatusChange",
        value: function _handleCurrentProductStatusChange(e) {
          if (this.id) {
            if (this.id !== e.addToCartId) {
              return;
            }

            if (e.productId) {
              this.productId = e.productId;
              this.options = e.options;
              this.quantity = e.quantity;
              this.settings = e.settings;
              var emptyRequiredField = false;
              var _iteratorNormalCompletion = true;
              var _didIteratorError = false;
              var _iteratorError = undefined;

              try {
                for (var _iterator = JSON.parse(this.options)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
                  var ddmFormValue = _step.value;

                  if (ddmFormValue.required === true) {
                    if (ddmFormValue.value.length === 0) {
                      emptyRequiredField = true;
                    } else {
                      var _iteratorNormalCompletion2 = true;
                      var _didIteratorError2 = false;
                      var _iteratorError2 = undefined;

                      try {
                        for (var _iterator2 = ddmFormValue.value[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
                          var val = _step2.value;

                          if (val === '' || val === null) {
                            emptyRequiredField = true;
                            break;
                          } else {
                            emptyRequiredField = false;
                          }
                        }
                      } catch (err) {
                        _didIteratorError2 = true;
                        _iteratorError2 = err;
                      } finally {
                        try {
                          if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
                            _iterator2.return();
                          }
                        } finally {
                          if (_didIteratorError2) {
                            throw _iteratorError2;
                          }
                        }
                      }
                    }
                  }

                  if (emptyRequiredField) {
                    break;
                  }
                }
              } catch (err) {
                _didIteratorError = true;
                _iteratorError = err;
              } finally {
                try {
                  if (!_iteratorNormalCompletion && _iterator.return != null) {
                    _iterator.return();
                  }
                } finally {
                  if (_didIteratorError) {
                    throw _iteratorError;
                  }
                }
              }

              if (emptyRequiredField) {
                this.disabled = true;
              } else {
                this.disabled = false;
              }
            } else {
              this.disabled = true;
            }
          }

          if (this.permissionDisabled) {
            this.disabled = true;
          }
        }
      }, {
        key: "_handleAccountChange",
        value: function _handleAccountChange(e) {
          this.accountId = e.accountId;
          this.orderId = null; // TODO: quantity should be imported from the outside

          this.quantity = 0;
          resetInputQuantity.call(this);
        }
      }, {
        key: "_handleCartProductRemoval",
        value: function _handleCartProductRemoval(_ref) {
          var skuId = _ref.skuId;

          if (skuId === parseInt(this.productId, 10) || skuId === ALL) {
            this.quantity = 0;
            resetInputQuantity.call(this);
          }
        }
      }, {
        key: "_handleSubmitClick",
        value: function _handleSubmitClick() {
          if (!this.accountId) {
            var message = Liferay.Language.get('no-account-selected');

            showNotification(message, 'danger');
          }

          if (this.disabled) {
            return null;
          }

          doSubmit.call(this);
        }
      }]);

      return AddToCartButton;
    }(_metalComponent.default);

    exports.AddToCartButton = AddToCartButton;

    _metalSoy.default.register(AddToCartButton, _AddToCartButton.default);

    AddToCartButton.STATE = {
      accountId: _metalSoy.Config.oneOfType([_metalSoy.Config.number(), _metalSoy.Config.string()]),
      buttonStyle: _metalSoy.Config.oneOf(['block', 'inline']).value('inline'),
      cartAPI: _metalSoy.Config.string().required(),
      disabled: _metalSoy.Config.bool().value(false),
      id: _metalSoy.Config.string(),
      inputQuantity: _metalSoy.Config.number(),
      options: _metalSoy.Config.oneOfType([_metalSoy.Config.object(), _metalSoy.Config.string()]).value('[]'),
      orderId: _metalSoy.Config.oneOfType([_metalSoy.Config.number(), _metalSoy.Config.string()]),
      permissionDisabled: _metalSoy.Config.bool().value(false),
      productId: _metalSoy.Config.oneOfType([_metalSoy.Config.number(), _metalSoy.Config.string()]).required(),
      quantity: _metalSoy.Config.number(),
      settings: _metalSoy.Config.shapeOf({
        allowedQuantity: _metalSoy.Config.array(_metalSoy.Config.number()),
        maxQuantity: _metalSoy.Config.number(),
        minQuantity: _metalSoy.Config.number(),
        multipleQuantity: _metalSoy.Config.number()
      }).value({}),
      textContent: _metalSoy.Config.string(),
      updatingTransition: _metalSoy.Config.oneOf(['adding', 'incrementing'])
    };
    var _default = AddToCartButton;
    exports.default = _default;
    //# sourceMappingURL=AddToCartButton.es.js.map
  }
});
//# sourceMappingURL=AddToCartButton.es.js.map