Liferay.Loader.define("commerce-frontend-taglib@10.0.15/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);
        } 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;
              this.disabled = false;
            } else {
              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()]),
      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