"use strict";

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); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _get = _interopRequireDefault(require("lodash/get"));
var _has = _interopRequireDefault(require("lodash/has"));
var _isArray = _interopRequireDefault(require("lodash/isArray"));
var _find = _interopRequireDefault(require("lodash/find"));
var _clsx = _interopRequireDefault(require("clsx"));
var _TextField = _interopRequireDefault(require("@material-ui/core/TextField"));
var _Grid = _interopRequireDefault(require("@material-ui/core/Grid"));
var _Typography = _interopRequireDefault(require("@material-ui/core/Typography"));
var _useMediaQuery = _interopRequireDefault(require("@material-ui/core/useMediaQuery"));
var _BlockRounded = _interopRequireDefault(require("@material-ui/icons/BlockRounded"));
var _InfoRounded = _interopRequireDefault(require("@material-ui/icons/InfoRounded"));
var _RestoreRounded = _interopRequireDefault(require("@material-ui/icons/RestoreRounded"));
var _WarningRounded = _interopRequireDefault(require("@material-ui/icons/WarningRounded"));
var _styles = require("@material-ui/core/styles");
var _Markdown = _interopRequireDefault(require("../../../../../Framework/Components/Markdown"));
var _i18n = require("../../../../../Framework/i18n");
var _customClassName = _interopRequireDefault(require("../../../../Utils/customClassName"));
var _OptionAmount = _interopRequireDefault(require("../OptionAmount"));
var _OptionGroup = _interopRequireDefault(require("../OptionGroup"));
var _getImageUrl = _interopRequireDefault(require("../../../../Utils/getImageUrl"));
var _AccessibleButton = _interopRequireDefault(require("../../../../Shared/Components/AccessibleButton/AccessibleButton"));
var _excluded = ["children", "render"];
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
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 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 _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); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
var styles = function styles(theme) {
  var textWidthWithAmount = theme.creator.option.image.width !== 'auto' ? "calc(94% - (".concat(theme.creator.option.image.width, " + 35px))") : theme.creator.option.textArea.textWidth;
  var customValues = {
    icon: {
      fontSize: '16px',
      lineHeight: 1.6
    },
    image: {
      fontSize: '11px',
      lineHeight: '11px'
    },
    textArea: {
      fontSize: '0.8em',
      title: {
        fontWeight: 'bold'
      }
    }
  };
  return {
    description: {},
    materialIcon: {},
    price: {},
    details: {},
    iconWithText: {
      lineHeight: customValues.icon.lineHeight,
      display: 'inline-flex',
      verticalAlign: 'middle',
      '& $materialIcon': {
        "float": 'left',
        display: 'inline-block',
        paddingRight: '8px',
        minWidth: '20px',
        textAlign: 'center'
      }
    },
    optionList: {
      overflow: 'hidden'
    },
    title: {
      fontWeight: 'bold',
      display: '-webkit-box',
      overflow: 'hidden',
      wordWrap: 'break-word',
      boxOrient: 'vertical',
      lineClamp: 3,
      textOverflow: 'ellipsis'
    },
    image: {
      display: 'inline-block',
      "float": 'left',
      height: '100%',
      maxHeight: '100%',
      maxWidth: theme.creator.option.image.width,
      marginRight: '10px',
      fontSize: 0,
      '& img': {
        maxHeight: '100%',
        maxWidth: '100%'
      },
      '& .imageNotAvailableElement': {
        padding: '4px',
        lineHeight: customValues.image.lineHeight,
        fontSize: customValues.image.fontSize
      }
    },
    root: {
      minHeight: '100px',
      padding: 10,
      cursor: 'pointer',
      fontSize: customValues.textArea.fontSize,
      display: 'flex',
      '& .content': {
        position: 'relative',
        display: 'flex',
        verticalAlign: 'middle',
        margin: 0,
        flex: 1
      },
      '& .disabled': {
        cursor: 'not-allowed',
        opacity: '0.8'
      },
      '&.selected': {
        backgroundColor: '#d8d8d8'
      },
      tapHighlightColor: theme.tapHighlightColor
    },
    text: {
      "float": 'left',
      width: 'calc(94% - ' + theme.creator.option.image.width + ')',
      '& a': {
        textDecoration: 'underline'
      },
      '& $description': {
        marginBottom: 10,
        '& p': {
          margin: 0
        }
      },
      '& $price': {
        marginBottom: 10
      },
      '& $title': {
        fontWeight: customValues.textArea.title.fontWeight,
        marginBottom: '10px'
      }
    },
    withAmount: {
      '& $text': {
        width: textWidthWithAmount
      }
    },
    optionTextInput: {}
  };
};
var Option = function Option(_ref) {
  var children = _ref.children,
    render = _ref.render,
    props = _objectWithoutProperties(_ref, _excluded);
  var className = props.className,
    onClick = props.onClick,
    onSelect = props.onSelect,
    onToggle = props.onToggle,
    onInputTextChange = props.onInputTextChange,
    option = props.option,
    optionclassification = props.optionclassification,
    selected = props.selected,
    viewDetails = props.viewDetails,
    viewStockInformation = props.viewStockInformation,
    OptionAmountComponent = props.OptionAmountComponent,
    OptionGroupComponent = props.OptionGroupComponent,
    classes = props.classes,
    isAdminMode = props.isAdminMode;
  var _useState = (0, _react.useState)(true),
    _useState2 = _slicedToArray(_useState, 2),
    imageAvailable = _useState2[0],
    setImageAvailable = _useState2[1];
  var selectedoptions = optionclassification.selectedoptions;
  var _useState3 = (0, _react.useState)((0, _get["default"])((0, _find["default"])(selectedoptions, ['identifier', option.identifier]), 'inputText', '')),
    _useState4 = _slicedToArray(_useState3, 2),
    inputText = _useState4[0],
    setInputText = _useState4[1];
  var query = new URLSearchParams(location.search);
  var hidePrices = query.has('_hide_prices') && query.get('_hide_prices') === '1';
  var smallerScreen = (0, _useMediaQuery["default"])('(min-device-width : 300px) and (max-device-width : 340px)');
  var thumbnail = (0, _get["default"])(option, 'thumbnail', '');
  var detailImage = (0, _get["default"])(option, 'detailImage');
  var optionIdentifier = (0, _get["default"])(option, 'identifier', '');
  var amountIsSelectable = (0, _get["default"])(option, 'amount_is_selectable', false);
  var resultStatus = (0, _get["default"])(option, 'check_results.status', true);
  var optionIsMultiSelect = (0, _get["default"])(option, 'is_multiselect', false);
  var optionAmount = (0, _get["default"])(option, 'amount', 0);
  var hasTextinput = (0, _get["default"])(option, 'hasTextinput', false);
  var translations = _objectSpread(_objectSpread({}, (0, _i18n.t)('common')), (0, _i18n.t)('optionlistitem'));
  var setImageAvailability = function setImageAvailability() {
    setImageAvailable(!imageAvailable);
  };
  var isEnabled = function isEnabled() {
    return (0, _get["default"])(option, 'stock.traffic_light', false) !== 'red';
  };
  var shouldDisplayDetails = function shouldDisplayDetails() {
    return option.description || detailImage;
  };
  var onOptionSelected = function onOptionSelected() {
    var optionClassificationIsMultiselect = (0, _get["default"])(optionclassification, 'is_multiselect', false);
    if (amountIsSelectable) {
      onSelect(_objectSpread(_objectSpread({}, option), {}, {
        amount: !optionAmount ? 1 : optionAmount
      }));
    } else if (optionClassificationIsMultiselect || isAdminMode) {
      onSelect(_objectSpread(_objectSpread({}, option), {}, {
        amount: selected ? 0 : 1
      }));
    } else if (!selected) {
      onSelect(_objectSpread(_objectSpread({}, option), {}, {
        amount: 1
      }));
    }
  };
  var onOptionClicked = function onOptionClicked(event) {
    event.preventDefault();
    event.stopPropagation();
    if (isEnabled() && !(hasTextinput && selected)) {
      onOptionSelected();
      onClick();
    }
  };
  var onAmountChanged = function onAmountChanged(optionAmount) {
    if (!isEnabled()) {
      return;
    }
    var amount;
    if (amountIsSelectable) {
      amount = optionAmount;
    } else if (optionIsMultiSelect) {
      amount = selected ? 0 : 1;
    } else if (!selected) {
      amount = 1;
    }
    if (amount < 0) {
      return; // prevent setting below 0
    }

    onSelect(_objectSpread(_objectSpread({}, option), {}, {
      amount: amount
    }));
  };
  var onAbstractClicked = function onAbstractClicked(event) {
    event.target.tagName.toLowerCase() === 'a' && event.stopPropagation();
  };
  var onDetailsClicked = function onDetailsClicked(event) {
    event.stopPropagation();
    event.preventDefault();
    if (isEnabled()) {
      viewDetails(option);
    }
  };
  var onIncompatibilityClicked = function onIncompatibilityClicked(event) {
    event.stopPropagation();
    event.preventDefault();
    if (isEnabled()) {
      onOptionSelected();
    }
  };
  var onOptionGroupClicked = function onOptionGroupClicked(event) {
    event.stopPropagation();
  };
  var onOptionGroupItemSelected = function onOptionGroupItemSelected(option) {
    onSelect(_objectSpread(_objectSpread({}, option), {}, {
      amount: 1
    }));
  };
  var onLateDeliveryClicked = function onLateDeliveryClicked(event) {
    event.stopPropagation();
    event.preventDefault();
    if (isEnabled()) {
      viewStockInformation(option);
    }
  };
  var renderImage = function renderImage() {
    var src = (0, _getImageUrl["default"])(thumbnail);
    return src && /*#__PURE__*/_react["default"].createElement("img", {
      src: src,
      alt: (0, _i18n.t)('ariaLabels.optionImage', {
        title: option.title
      }),
      onError: setImageAvailability
    });
  };
  var renderNotAvailableImage = function renderNotAvailableImage() {
    return /*#__PURE__*/_react["default"].createElement("div", {
      className: 'imageNotAvailableElement'
    }, /*#__PURE__*/_react["default"].createElement(_Typography["default"], {
      variant: 'caption'
    }, translations.imageNotAvailable));
  };
  var renderStockStatus = function renderStockStatus() {
    if (option.stock) {
      switch (option.stock.traffic_light) {
        case 'red':
          return /*#__PURE__*/_react["default"].createElement("div", {
            className: classes.iconWithText
          }, /*#__PURE__*/_react["default"].createElement(_BlockRounded["default"], {
            className: classes.materialIcon
          }), ' ', /*#__PURE__*/_react["default"].createElement(_Typography["default"], {
            variant: 'body2'
          }, translations.notAvailable));
        case 'yellow':
          return /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement(_AccessibleButton["default"], {
            component: "a",
            className: classes.iconWithText,
            onClick: onLateDeliveryClicked
          }, /*#__PURE__*/_react["default"].createElement(_RestoreRounded["default"], {
            className: classes.materialIcon
          }), ' ', /*#__PURE__*/_react["default"].createElement(_Typography["default"], {
            variant: 'body2'
          }, translations.lateDelivery)));
        case 'green':
          return null;
      }
    }
    return null;
  };
  var renderOptionGroup = function renderOptionGroup() {
    if (!isEnabled()) {
      return null;
    }
    var optionGroup = (0, _get["default"])(option, 'option_group', {});
    if ((0, _has["default"])(optionGroup, 'children') && (0, _isArray["default"])(optionGroup.children) && optionGroup.children.length > 0) {
      return /*#__PURE__*/_react["default"].createElement("div", {
        onClick: onOptionGroupClicked
      }, /*#__PURE__*/_react["default"].createElement(OptionGroupComponent, {
        itemGroup: optionGroup,
        option: option,
        optionclassification: optionclassification,
        onOptionSelect: onOptionGroupItemSelected,
        selected: selected,
        onToggle: onToggle
      }));
    }
    return null;
  };
  var renderActions = function renderActions() {
    var displayDetails = shouldDisplayDetails();
    return /*#__PURE__*/_react["default"].createElement("div", {
      className: classes.details
    }, displayDetails && /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement(_AccessibleButton["default"], {
      component: "a",
      className: classes.iconWithText,
      onClick: onDetailsClicked
    }, /*#__PURE__*/_react["default"].createElement(_InfoRounded["default"], {
      className: (0, _clsx["default"])(classes.materialIcon, (0, _customClassName["default"])('rule-info-icon-option'))
    }), /*#__PURE__*/_react["default"].createElement(_Typography["default"], {
      variant: 'body2',
      className: classes.iconWithText
    }, translations.details))), resultStatus !== true && /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement("a", {
      className: classes.iconWithText,
      onClick: onIncompatibilityClicked
    }, /*#__PURE__*/_react["default"].createElement(_WarningRounded["default"], {
      className: (0, _clsx["default"])(classes.materialIcon, (0, _customClassName["default"])('rule-alert-icon-option'))
    }), /*#__PURE__*/_react["default"].createElement(_Typography["default"], {
      variant: 'body2'
    }, translations.incompatibility))), renderStockStatus(), renderOptionGroup());
  };
  var renderText = function renderText() {
    return /*#__PURE__*/_react["default"].createElement(_Grid["default"], {
      item: true,
      xs: 12
    }, /*#__PURE__*/_react["default"].createElement(_Typography["default"], {
      component: 'div',
      className: classes.optionList,
      variant: 'body2'
    }, /*#__PURE__*/_react["default"].createElement("div", {
      className: classes.title
    }, option.title), hasTextinput && renderTextInput(), !hidePrices && /*#__PURE__*/_react["default"].createElement("div", {
      className: classes.price
    }, option.priceFormatted), smallerScreen && renderControls('horizontal'), option["abstract"] && /*#__PURE__*/_react["default"].createElement(_Markdown["default"], {
      className: classes.description,
      onClick: onAbstractClicked
    }, option["abstract"]), renderActions()));
  };
  var renderControls = function renderControls(view) {
    if (isEnabled() && amountIsSelectable && OptionAmountComponent) {
      return /*#__PURE__*/_react["default"].createElement(OptionAmountComponent, {
        view: view,
        option: option,
        onAmountChange: onAmountChanged,
        onSelect: onSelect
      });
    } else {
      return null;
    }
  };
  var handleTextInputChange = function handleTextInputChange(event) {
    setInputText(event.target.value);
    onInputTextChange(option.identifier, event.target.value);
  };
  var renderTextInput = function renderTextInput() {
    return /*#__PURE__*/_react["default"].createElement(_TextField["default"], {
      className: classes.optionTextInput,
      label: '',
      value: inputText,
      onChange: handleTextInputChange,
      disabled: !selected,
      translate: "no"
    });
  };
  var getRootClassName = function getRootClassName() {
    return (0, _clsx["default"])(classes.root, selected && 'selected', (0, _customClassName["default"])('option'));
  };
  var getContentClassName = function getContentClassName() {
    var amountClass = amountIsSelectable && !smallerScreen ? classes.withAmount : '';
    return (0, _clsx["default"])('content', className, optionIdentifier, amountClass, !isEnabled() && 'disabled', resultStatus !== true && 'incompatible');
  };
  var getRenderProps = function getRenderProps() {
    return _objectSpread(_objectSpread({}, props), {}, {
      imageAvailable: imageAvailable,
      smallerScreen: smallerScreen,
      renderImage: renderImage,
      renderNotAvailableImage: renderNotAvailableImage,
      renderText: renderText,
      renderControls: renderControls,
      renderActions: renderActions,
      renderOptionGroup: renderOptionGroup,
      renderStockStatus: renderStockStatus,
      setImageAvailability: setImageAvailability,
      isEnabled: isEnabled,
      shouldDisplayDetails: shouldDisplayDetails,
      onOptionSelected: onOptionSelected,
      onOptionClicked: onOptionClicked,
      onAmountChanged: onAmountChanged,
      onAbstractClicked: onAbstractClicked,
      onDetailsClicked: onDetailsClicked,
      onIncompatibilityClicked: onIncompatibilityClicked,
      onOptionGroupClicked: onOptionGroupClicked,
      onOptionGroupItemSelected: onOptionGroupItemSelected,
      onLateDeliveryClicked: onLateDeliveryClicked,
      getRootClassName: getRootClassName,
      getContentClassName: getContentClassName
    });
  };
  var renderItem = function renderItem() {
    return /*#__PURE__*/_react["default"].createElement(_AccessibleButton["default"], {
      component: "div",
      className: getRootClassName(),
      "data-option": option.identifier,
      onClick: onOptionClicked,
      notAccessible: props.notAccessible
    }, /*#__PURE__*/_react["default"].createElement("div", {
      className: getContentClassName()
    }, typeof children === 'function' ? children(getRenderProps()) : /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement("div", {
      className: classes.image
    }, imageAvailable ? renderImage() : renderNotAvailableImage()), /*#__PURE__*/_react["default"].createElement("div", {
      className: classes.text
    }, renderText()), !smallerScreen && renderControls())));
  };
  return typeof render === 'function' ? render(getRenderProps()) : renderItem();
};
Option.defaultProps = {
  className: '',
  onClick: function onClick() {},
  onSelect: function onSelect() {},
  onToggle: function onToggle() {},
  onInputTextChange: function onInputTextChange() {},
  optionclassification: {},
  option: {},
  selected: false,
  translations: {},
  viewDetails: function viewDetails() {},
  viewStockInformation: function viewStockInformation() {},
  OptionAmountComponent: _OptionAmount["default"],
  OptionGroupComponent: _OptionGroup["default"],
  notAccessible: false
};
var _default = exports["default"] = (0, _styles.withStyles)(styles, {
  name: 'Option'
})(Option);