"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.hasError = exports["default"] = void 0;
var _react = _interopRequireDefault(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _styles = require("@material-ui/core/styles");
var _withWidth = _interopRequireWildcard(require("@material-ui/core/withWidth"));
var _i18n = require("../../../../Framework/i18n");
var _Grid = _interopRequireDefault(require("@material-ui/core/Grid"));
var _AmountInput = _interopRequireDefault(require("../AmountInput"));
var _isFunction = _interopRequireDefault(require("lodash/isFunction"));
var _get = _interopRequireDefault(require("lodash/get"));
var _find = _interopRequireDefault(require("lodash/find"));
var _sum = _interopRequireDefault(require("lodash/sum"));
var _isEmpty = _interopRequireDefault(require("lodash/isEmpty"));
var _upperFirst = _interopRequireDefault(require("lodash/upperFirst"));
var _ListItem = _interopRequireDefault(require("@material-ui/core/ListItem"));
var _Button = _interopRequireDefault(require("@material-ui/core/Button"));
var _Typography = _interopRequireDefault(require("@material-ui/core/Typography"));
var _Icon = _interopRequireDefault(require("@material-ui/core/Icon"));
var _BulkNames = _interopRequireDefault(require("../../Containers/BulkNames"));
var _Image = _interopRequireDefault(require("./Image"));
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
function _createSuper(t) { var r = _isNativeReflectConstruct(); return function () { var e, o = _getPrototypeOf(t); if (r) { var s = _getPrototypeOf(this).constructor; e = Reflect.construct(o, arguments, s); } else e = o.apply(this, arguments); return _possibleConstructorReturn(this, e); }; }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
var styles = function styles(theme) {
  var _ButtonOutlinedRoot, _productAmounts;
  return {
    ProductVariantRoot: _defineProperty({
      height: 'auto',
      alignItems: 'flex-start',
      paddingLeft: 0
    }, theme.breakpoints.down('xs'), {
      paddingRight: 0
    }),
    ButtonOutlinedRoot: (_ButtonOutlinedRoot = {
      fontWeight: 'bold',
      textTransform: 'none',
      whiteSpace: 'nowrap'
    }, _defineProperty(_ButtonOutlinedRoot, theme.breakpoints.down('xs'), {
      minWidth: 35,
      padding: 0
    }), _defineProperty(_ButtonOutlinedRoot, theme.breakpoints.up('sm'), {
      display: 'block'
    }), _ButtonOutlinedRoot),
    ButtonOutlinedRootLabel: {
      fontWeight: 'bold'
    },
    ProductVariantImageItem: {
      width: 100,
      height: 100,
      marginRight: 16,
      maxWidth: 100
    },
    ProductVariantImageItemSizeSelect: {
      marginRight: 16,
      maxWidth: 100
    },
    productAmounts: (_productAmounts = {}, _defineProperty(_productAmounts, theme.breakpoints.up('sm'), {
      width: 200,
      maxWidth: 200,
      minWidth: 200
    }), _defineProperty(_productAmounts, theme.breakpoints.down('sm'), {
      maxWidth: 225
    }), _productAmounts),
    selectedCheck: {
      whiteSpace: 'nowrap',
      paddingBottom: 8
    },
    TypographyBody1: {
      lineHeight: 2.5,
      display: 'flex',
      justifyContent: 'space-between'
    },
    ProductVariantImage: {
      width: '100px',
      height: '100px',
      maxWidth: 190,
      objectFit: 'contain'
    },
    ProductVariantImageSelected: {
      maxWidth: 210,
      width: '100px',
      height: '100px',
      objectFit: 'contain'
    },
    deleteIcon: {
      lineHeight: '1.3',
      '&:hover': {
        cursor: 'pointer'
      }
    },
    amountVariants: _defineProperty({
      '&.MuiFormControl-marginNormal': {
        marginTop: 4
      },
      width: 95
    }, theme.breakpoints.down('xs'), {
      width: 'calc(50% - 5px)'
    }),
    amountVariant: _defineProperty({
      width: 150
    }, theme.breakpoints.down('xs'), {
      width: '100%'
    }),
    gridFlowList: function gridFlowList(_ref) {
      var width = _ref.width,
        showReceiveOfferForm = _ref.showReceiveOfferForm,
        amountData = _ref.amountData;
      return {
        position: 'relative',
        display: 'grid',
        width: '100%',
        gridAutoFlow: !showReceiveOfferForm && !(0, _withWidth.isWidthDown)('sm', width) ? 'column' : '',
        gridTemplateRows: !showReceiveOfferForm && !(0, _withWidth.isWidthDown)('sm', width) ? 'repeat(' + Math.round(amountData.length / 2) + ', auto)' : ''
      };
    },
    checkIcon: {
      lineHeight: '1.5'
    }
  };
};
var hasError = exports.hasError = function hasError(identifier, errors) {
  if (!errors) {
    return false;
  }
  var error = (0, _find["default"])(errors.errors, function (o) {
    return o.itemIdentifier === identifier;
  });
  return !!error;
};
var ProductVariant = /*#__PURE__*/function (_React$Component) {
  _inherits(ProductVariant, _React$Component);
  var _super = _createSuper(ProductVariant);
  function ProductVariant() {
    var _this;
    _classCallCheck(this, ProductVariant);
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _super.call.apply(_super, [this].concat(args));
    _defineProperty(_assertThisInitialized(_this), "state", {
      activeItem: null,
      sizes: {},
      showBulkNameForm: false,
      activeVariantItem: {},
      activeSize: {}
    });
    _defineProperty(_assertThisInitialized(_this), "handleChange", function (variant, size) {
      return function (value) {
        //variant sizes length should be > 1 because the button for saving is then visible
        if (variant && variant.sizes && variant.sizes.length > 1 && size && size.identifier) {
          _this.setState(function (state) {
            return {
              sizes: _objectSpread(_objectSpread({}, state.sizes), {}, _defineProperty({}, size.identifier, value))
            };
          });
        } else {
          if ((0, _isFunction["default"])(_this.props.handleChange)) {
            _this.props.handleChange(variant, size, value);
          }
        }
      };
    });
    _defineProperty(_assertThisInitialized(_this), "handleFocus", function (event) {
      // select text async for mac os safari
      var target = event.target;
      setTimeout(function () {
        return target.select();
      }, 0);
    });
    _defineProperty(_assertThisInitialized(_this), "handleOpenSizeClick", function (activeItem) {
      return function () {
        _this.setState({
          activeItem: activeItem
        });
      };
    });
    _defineProperty(_assertThisInitialized(_this), "handleBulkNameForm", function (variant, size) {
      return function () {
        var activeBulkNames = _this.props.activeBulkNames;
        if (!activeBulkNames) {
          return;
        }
        _this.setState({
          showBulkNameForm: true,
          activeVariantItem: variant,
          activeSize: size || _this.state.activeSize
        });
      };
    });
    _defineProperty(_assertThisInitialized(_this), "handleBulkNamesFormClose", function () {
      _this.setState({
        showBulkNameForm: false
      });
    });
    _defineProperty(_assertThisInitialized(_this), "handleBulkNamesSave", function (identifier, bulkNamesData) {
      if ((0, _isFunction["default"])(_this.props.saveConfigurationBulkNames)) {
        _this.props.saveConfigurationBulkNames(identifier, bulkNamesData);
      }
    });
    _defineProperty(_assertThisInitialized(_this), "handleConfirmSize", function (variant) {
      if ((0, _isFunction["default"])(_this.props.handleMultipleAmountInputsChange)) {
        _this.props.handleMultipleAmountInputsChange(variant, _this.state.sizes);
      }
      _this.setState({
        activeItem: null
      });
    });
    _defineProperty(_assertThisInitialized(_this), "deleteAllSelectedAmount", function (variant) {
      if ((0, _isFunction["default"])(_this.props.deleteSelectedAmounts)) {
        _this.props.deleteSelectedAmounts(variant, _this.state.sizes);
      }
    });
    return _this;
  }
  _createClass(ProductVariant, [{
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps, prevState) {
      var amountMap = this.props.amountMap;
      var activeItem = this.state.activeItem;
      if (amountMap !== prevProps.amountMap || activeItem !== prevState.activeItem) {
        this.setState({
          sizes: amountMap
        });
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;
      var _this$props = this.props,
        classes = _this$props.classes,
        amountData = _this$props.amountData,
        header = _this$props.header,
        error = _this$props.error,
        BulkNamesComponent = _this$props.BulkNamesComponent,
        activeBulkNames = _this$props.activeBulkNames,
        previewImages = _this$props.previewImages,
        variantListLoaderElement = _this$props.variantListLoaderElement;
      var _this$state = this.state,
        showBulkNameForm = _this$state.showBulkNameForm,
        activeVariantItem = _this$state.activeVariantItem,
        activeSize = _this$state.activeSize;
      if (!amountData || amountData.length === 0) {
        return null;
      }
      var bulkNameVariant = (0, _isEmpty["default"])(activeSize) ? activeVariantItem : activeSize;
      return /*#__PURE__*/_react["default"].createElement(_Grid["default"], {
        container: true
      }, header && /*#__PURE__*/_react["default"].createElement(_Typography["default"], {
        variant: "body1"
      }, /*#__PURE__*/_react["default"].createElement("b", null, header)), /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.gridFlowList
      }, variantListLoaderElement, amountData.map(function (variant, i) {
        if (variant.isDisabled === true) {
          return null;
        }
        var isSelected = _this2.state.activeItem ? variant.identifier === _this2.state.activeItem.identifier : variant === _this2.state.activeItem;
        var variantAmountSum = (0, _sum["default"])(variant.sizes.map(function (variantSize) {
          return Number(variantSize.amount);
        }));
        var rootProps = variant.sizes.length > 1 ? classes.amountVariants : classes.amountVariant;
        var imageSrc = (0, _get["default"])(previewImages, variant.identifier) || variant.url;
        return /*#__PURE__*/_react["default"].createElement(_ListItem["default"], {
          key: i,
          value: variant.title,
          "aria-label": variant.title,
          className: classes.ProductVariantRoot
        }, /*#__PURE__*/_react["default"].createElement(_Grid["default"], {
          item: true,
          xs: isSelected ? 4 : 5,
          classes: {
            item: !isSelected ? classes.ProductVariantImageItem : classes.ProductVariantImageItemSizeSelect
          }
        }, imageSrc && /*#__PURE__*/_react["default"].createElement(_Image["default"], {
          src: imageSrc,
          alt: variant.title,
          "aria-label": variant.title,
          className: isSelected ? classes.ProductVariantImageSelected : classes.ProductVariantImage
        })), /*#__PURE__*/_react["default"].createElement(_Grid["default"], {
          item: true,
          xs: 8,
          className: classes.productAmounts
        }, /*#__PURE__*/_react["default"].createElement(_Typography["default"], {
          variant: "body1",
          classes: {
            root: classes.TypographyBody1
          }
        }, /*#__PURE__*/_react["default"].createElement("b", null, " ", (0, _upperFirst["default"])(variant.title))), !isSelected && variant.sizes.length > 1 && /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, variantAmountSum > 0 && /*#__PURE__*/_react["default"].createElement(_Typography["default"], {
          variant: "body1",
          className: classes.selectedCheck,
          classes: {
            root: classes.TypographyBody1
          }
        }, /*#__PURE__*/_react["default"].createElement(_Icon["default"], {
          className: classes.checkIcon
        }, "check"), /*#__PURE__*/_react["default"].createElement("b", null, (0, _i18n.t)('productVariant.amountChosen')), variantAmountSum > 0 && variantAmountSum, /*#__PURE__*/_react["default"].createElement(_Icon["default"], {
          className: classes.deleteIcon,
          onClick: function onClick() {
            return _this2.deleteAllSelectedAmount(variant);
          }
        }, "delete_forever")), /*#__PURE__*/_react["default"].createElement(_Button["default"], {
          variant: "outlined",
          onClick: _this2.handleOpenSizeClick(variant),
          classes: {
            root: classes.ButtonOutlinedRoot
          },
          fullWidth: true
        }, (0, _i18n.t)(variant.amount > 0 ? 'productVariant.adaptSizes' : 'productVariant.chooseSize'))), (isSelected || variant.sizes.length === 1) && /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, variant.sizes.map(function (size) {
          return /*#__PURE__*/_react["default"].createElement(_AmountInput["default"], {
            value: size.amount,
            amountLabel: size.label.split(' ').pop(),
            key: size.size,
            onChange: _this2.handleChange(variant, size),
            onClick: _this2.handleBulkNameForm(variant, size),
            error: hasError(size.identifier, error),
            disabled: variant.isDisabled,
            onChangeDebounceWait: 0,
            readOnly: activeBulkNames,
            rootProps: rootProps,
            onFocus: _this2.handleFocus
          });
        }), variant.sizes.length > 1 && /*#__PURE__*/_react["default"].createElement(_Button["default"], {
          fullWidth: true,
          variant: "outlined",
          onClick: function onClick() {
            return _this2.handleConfirmSize(variant);
          },
          classes: {
            root: classes.ButtonOutlinedRoot,
            label: classes.ButtonOutlinedRootLabel
          }
        }, (0, _i18n.t)('productVariant.confirmSelection'))), (0, _get["default"])(variant, 'sizes.length', 0) === 0 && /*#__PURE__*/_react["default"].createElement(_AmountInput["default"], {
          value: variant.amount + ' ' + (0, _i18n.t)('amountSelection.amount'),
          hasValueLabel: true,
          amountLabel: (0, _i18n.t)('productVariant.amountLabel'),
          onChange: _this2.handleChange(variant),
          onClick: _this2.handleBulkNameForm(variant),
          error: hasError(variant.identifier, error),
          disabled: variant.isDisabled,
          readOnly: activeBulkNames,
          onChangeDebounceWait: 0,
          rootProps: rootProps,
          onFocus: _this2.handleFocus
        })));
      }), showBulkNameForm && /*#__PURE__*/_react["default"].createElement(BulkNamesComponent, {
        selectedAmount: amountData,
        selectedVariant: activeVariantItem,
        activeSizeVariant: activeSize,
        amountLabel: (0, _i18n.t)('productVariant.amountLabel'),
        handleChange: this.handleChange(bulkNameVariant),
        onClose: this.handleBulkNamesFormClose,
        handleSave: this.handleBulkNamesSave,
        showBulkNameForm: showBulkNameForm
      })));
    }
  }]);
  return ProductVariant;
}(_react["default"].Component);
_defineProperty(ProductVariant, "defaultProps", {
  BulkNamesComponent: _BulkNames["default"],
  previewImages: {}
});
var _default = exports["default"] = (0, _withWidth["default"])({
  initialWidth: 'lg'
})((0, _styles.withStyles)(styles, {
  name: 'ProductVariant'
})(ProductVariant));