"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
var _react = _interopRequireDefault(require("react"));
var _find = _interopRequireDefault(require("lodash/find"));
var _findIndex = _interopRequireDefault(require("lodash/findIndex"));
var _isArray = _interopRequireDefault(require("lodash/isArray"));
var _reactSwipeable = require("react-swipeable");
var _clsx2 = _interopRequireDefault(require("clsx"));
var _Button = _interopRequireDefault(require("@material-ui/core/Button"));
var _DialogContent = _interopRequireDefault(require("@material-ui/core/DialogContent"));
var _Typography = _interopRequireDefault(require("@material-ui/core/Typography"));
var _DialogActions = _interopRequireDefault(require("@material-ui/core/DialogActions"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _styles = require("@material-ui/core/styles");
var _withWidth = _interopRequireDefault(require("@material-ui/core/withWidth"));
var _configuration = require("../../../../configuration");
var _LoadingOverlay = _interopRequireDefault(require("../../../../../Framework/Components/LoadingOverlay"));
var _i18n = require("../../../../../Framework/i18n");
var _CustomDialog = _interopRequireDefault(require("../../../../../Shared/Components/CustomDialog"));
var _OptionAmount = _interopRequireDefault(require("../OptionAmount"));
var _getImageUrl = _interopRequireDefault(require("../../../../Utils/getImageUrl"));
var _Markdown = _interopRequireDefault(require("../../../../../Framework/Components/Markdown"));
var _ZoomImage = _interopRequireDefault(require("./ZoomImage"));
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) {
  return {
    detailNav: {
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      cursor: 'pointer',
      fontWeight: 'bold',
      fontSize: '72px',
      transform: 'scaleX(0.5)',
      opacity: 0.7,
      '&.prev': {
        '&:before': {
          content: '"<"'
        }
      },
      '&.next': {
        '&:before': {
          content: '">"'
        }
      }
    },
    detailFooter: {
      clear: 'both',
      padding: '10px 0 0 32px',
      textAlign: 'right',
      '& button': {
        marginLeft: 10,
        background: theme.palette.primary.darkText,
        color: 'white',
        '&:hover': {
          cursor: 'pointer',
          backgroundColor: '#616161'
        }
      }
    },
    detailContainerWithNav: {
      display: 'grid',
      gridTemplateColumns: 'auto 1fr auto'
    },
    detailContainer: {},
    detailsWithImageContainer: {
      display: 'grid',
      gridTemplateColumns: 'minMax(300px, 4fr) 6fr',
      columnGap: 24
    },
    priceFormatted: {
      marginTop: 32,
      marginBottom: 32
    },
    detailsTitle: {
      fontWeight: 'bold'
    },
    detailsTypography: {
      marginTop: 12,
      marginBottom: 12
    },
    imageContainer: {
      display: 'grid',
      placeItems: 'start center'
    },
    imageContainerWithZoom: {
      display: 'grid',
      placeItems: 'start center',
      cursor: 'zoom-in'
    },
    image: {
      marginTop: 12,
      maxWidth: '100%',
      maxHeight: '100%'
    },
    imageHidden: {
      visibility: 'hidden'
    },
    dialogContentRootWithZoom: {
      overflow: 'hidden'
    },
    detailDialogContentRoot: {
      overflowY: 'auto'
    }
  };
};
var Optiondetail = /*#__PURE__*/function (_React$Component) {
  _inherits(Optiondetail, _React$Component);
  var _super = _createSuper(Optiondetail);
  function Optiondetail(props) {
    var _this;
    _classCallCheck(this, Optiondetail);
    _this = _super.call(this, props);
    _defineProperty(_assertThisInitialized(_this), "prev", function () {
      var _this$props = _this.props,
        details = _this$props.details,
        options = _this$props.options,
        viewDetails = _this$props.viewDetails;
      if (options.length) {
        var optionIndex = (0, _findIndex["default"])(options, {
          identifier: details.identifier
        });
        var prevIndex = optionIndex === 0 ? options.length - 1 : optionIndex - 1;
        var prev = options[prevIndex];
        viewDetails(prev);
        _this.setState({
          currentOption: prev,
          loading: true,
          loadingContainerHeight: _this.detailContainerRef.clientHeight
        });
      }
    });
    _defineProperty(_assertThisInitialized(_this), "next", function () {
      var _this$props2 = _this.props,
        details = _this$props2.details,
        options = _this$props2.options,
        viewDetails = _this$props2.viewDetails;
      if (options.length) {
        var optionIndex = (0, _findIndex["default"])(options, {
          identifier: details.identifier
        });
        var nextIndex = optionIndex === options.length - 1 ? 0 : optionIndex + 1;
        var next = options[nextIndex];
        viewDetails(next);
        _this.setState({
          currentOption: next,
          loading: true,
          loadingContainerHeight: _this.detailContainerRef.clientHeight
        });
      }
    });
    _defineProperty(_assertThisInitialized(_this), "swiped", function (e, deltaX, deltaY) {
      // use only horizontal swiping
      if (Math.abs(deltaX) >= Math.abs(deltaY)) {
        if (deltaX > 0) {
          _this.next();
        } else {
          _this.prev();
        }
      }
    });
    _defineProperty(_assertThisInitialized(_this), "handleImageLoaded", function () {
      return _this.setState({
        imageStatus: 'loaded'
      });
    });
    _defineProperty(_assertThisInitialized(_this), "toggleZoomImage", function () {
      return _this.setState({
        zoomImage: !_this.state.zoomImage
      });
    });
    _defineProperty(_assertThisInitialized(_this), "setDetailsImageRef", function (ref) {
      _this.detailImageRef = ref;
    });
    _defineProperty(_assertThisInitialized(_this), "setDetailsContainerRef", function (ref) {
      _this.detailContainerRef = ref;
    });
    _defineProperty(_assertThisInitialized(_this), "getMaxZoomedWidth", function (width) {
      var isWideScreen = width === 'sm' || width === 'md' || width === 'lg' || width === 'xl';
      var maxZoomedWidth = width === 'xl' ? 1080 : 720;
      return isWideScreen ? maxZoomedWidth : '100%';
    });
    var _details = props.details,
      _options = props.options;
    _this.state = {
      currentOption: (0, _find["default"])(_options, {
        identifier: _details.identifier
      }),
      loading: false,
      zoomImage: false,
      hasZoomSet: false,
      hasZoom: false,
      imageStatus: 'loading'
    };
    _this.optionDetailsWithImage = (0, _configuration.getConf)('optionDetailsWithImage') || false;
    _this.detailContainerRef = /*#__PURE__*/_react["default"].createRef();
    _this.detailImageRef = /*#__PURE__*/_react["default"].createRef();
    return _this;
  }
  _createClass(Optiondetail, [{
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      var _this$props3 = this.props,
        details = _this$props3.details,
        options = _this$props3.options;
      if (details.identifier !== prevProps.details.identifier) {
        this.setState({
          currentOption: (0, _find["default"])(options, {
            identifier: details.identifier
          }),
          loading: false
        });
      }
    }
  }, {
    key: "getOptionData",
    value: function getOptionData() {
      if (!this.state.currentOption) {
        return null;
      }
      var optionclassification = this.props.optionclassification;
      var currentOption = this.state.currentOption;
      var identifier = currentOption.identifier;
      return (0, _find["default"])(optionclassification.selectedoptions, {
        identifier: identifier
      }) || currentOption;
    }
  }, {
    key: "onAmountChange",
    value: function onAmountChange(delta) {
      var onSelect = this.props.onSelect;
      var option = this.getOptionData();
      var amount = option.amount + delta;
      if (amount < 0) {
        return; // prevent setting below 0
      }

      onSelect(_objectSpread(_objectSpread({}, option), {}, {
        amount: amount
      }), true, true);
    }
  }, {
    key: "onSelect",
    value: function onSelect() {
      var _this$props4 = this.props,
        onSelect = _this$props4.onSelect,
        onClose = _this$props4.onClose;
      // just close it if it's already selected
      if (this.state.currentOption.amount > 0) {
        onClose && onClose();
      } else {
        onSelect(_objectSpread(_objectSpread({}, this.state.currentOption), {}, {
          amount: this.state.currentOption.amount || 1
        }));
      }
    }
  }, {
    key: "renderControls",
    value: function renderControls() {
      var OptionlistitemAmount = this.props.OptionlistitemAmount;
      var option = this.getOptionData();
      if (!option) {
        return null;
      }
      if (option.amount_is_selectable) {
        return /*#__PURE__*/_react["default"].createElement(OptionlistitemAmount, {
          option: option,
          onAmountChange: this.onAmountChange.bind(this)
        });
      } else {
        return /*#__PURE__*/_react["default"].createElement(_Button["default"], {
          className: "primary-button",
          onClick: this.onSelect.bind(this),
          variant: "contained"
        }, (0, _i18n.T)('optiondetail.choose'));
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props5 = this.props,
        LoadingComponent = _this$props5.LoadingComponent,
        options = _this$props5.options,
        show = _this$props5.show,
        onClose = _this$props5.onClose,
        details = _this$props5.details,
        classes = _this$props5.classes,
        width = _this$props5.width,
        optionclassification = _this$props5.optionclassification;
      var _this$state = this.state,
        loading = _this$state.loading,
        loadingContainerHeight = _this$state.loadingContainerHeight;
      var showNav = (0, _isArray["default"])(options) && options.length > 1;
      var detailImage = details.detailImage;
      var query = new URLSearchParams(location.search);
      var hidePrices = query.has('_hide_prices') && query.get('_hide_prices') === '1';
      var detailsContent = /*#__PURE__*/_react["default"].createElement("div", null, details["abstract"] && /*#__PURE__*/_react["default"].createElement(_Markdown["default"], {
        MdComponent: _Typography["default"],
        variant: "body2",
        component: "div",
        className: classes.detailsTypography
      }, details["abstract"]), !hidePrices && /*#__PURE__*/_react["default"].createElement(_Typography["default"], {
        component: "div",
        variant: "body2",
        className: classes.priceFormatted
      }, details.priceFormatted), details.description && /*#__PURE__*/_react["default"].createElement(_Markdown["default"], {
        MdComponent: _Typography["default"],
        variant: "body2",
        component: "div",
        className: classes.detailsTypography
      }, details.description));
      var showFullScreenModal = ['xs', 'sm'].includes(width);
      var maxZoomedWidth = this.getMaxZoomedWidth(width);
      var isLandscapeFormat = false;
      if (!!this.detailImageRef && this.detailImageRef.current !== null && this.state.imageStatus === 'loaded') {
        if (this.detailImageRef.naturalHeight < this.detailImageRef.naturalWidth) {
          isLandscapeFormat = true;
        }
        if (!this.state.hasZoomSet) {
          var hasZoom = this.detailImageRef.naturalHeight * this.detailImageRef.naturalWidth >= 1.2 * this.detailImageRef.width * this.detailImageRef.height;
          this.setState({
            hasZoomSet: true,
            hasZoom: hasZoom
          });
        }
        if (this.detailImageRef.naturalWidth < 720) {
          maxZoomedWidth = this.detailImageRef.naturalWidth;
        }
      }
      return /*#__PURE__*/_react["default"].createElement(_CustomDialog["default"], {
        open: show,
        dialogTitle: details.title,
        onClose: onClose,
        onCancel: onClose,
        fullScreen: showFullScreenModal
      }, /*#__PURE__*/_react["default"].createElement(_DialogContent["default"], {
        classes: this.state.hasZoom ? {
          root: (0, _clsx2["default"])(classes.detailDialogContentRoot, classes.dialogContentRootWithZoom)
        } : {
          root: classes.detailDialogContentRoot
        }
      }, loading ? /*#__PURE__*/_react["default"].createElement("div", {
        style: {
          height: loadingContainerHeight,
          boxSizing: 'border-box'
        }
      }, /*#__PURE__*/_react["default"].createElement(LoadingComponent, {
        show: loading
      })) : /*#__PURE__*/_react["default"].createElement(_reactSwipeable.Swipeable, {
        disabled: !showNav,
        trackMouse: true,
        onSwiped: this.swiped,
        delta: Optiondetail.swipeDelta
      }, /*#__PURE__*/_react["default"].createElement("div", {
        ref: this.setDetailsContainerRef,
        className: showNav ? classes.detailContainerWithNav : classes.detailContainer
      }, showNav && /*#__PURE__*/_react["default"].createElement("div", {
        className: (0, _clsx2["default"])(classes.detailNav, 'prev'),
        onClick: this.prev
      }), detailImage ? /*#__PURE__*/_react["default"].createElement("div", {
        className: (0, _clsx2["default"])(_defineProperty({}, classes.detailsWithImageContainer, !showFullScreenModal))
      }, /*#__PURE__*/_react["default"].createElement("div", {
        className: this.state.hasZoom ? classes.imageContainerWithZoom : classes.imageContainer,
        onClick: this.state.hasZoom ? this.toggleZoomImage : null
      }, /*#__PURE__*/_react["default"].createElement("img", {
        ref: this.setDetailsImageRef,
        onLoad: this.handleImageLoaded,
        className: this.state.zoomImage && ['xs', 'sm'].includes(width) ? classes.imageHidden : classes.image,
        src: (0, _getImageUrl["default"])(detailImage),
        alt: (0, _i18n.T)('ariaLabels.optionDetailsImage', {
          componentTitle: optionclassification.title,
          optionTitle: details.title
        })
      })), detailsContent) : detailsContent, showNav && /*#__PURE__*/_react["default"].createElement("div", {
        className: (0, _clsx2["default"])(classes.detailNav, 'next'),
        onClick: this.next
      })))), /*#__PURE__*/_react["default"].createElement(_DialogActions["default"], null, /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.detailFooter
      }, this.renderControls())), /*#__PURE__*/_react["default"].createElement(_ZoomImage["default"], {
        onClose: this.toggleZoomImage,
        show: this.state.zoomImage,
        image: detailImage,
        loadingContainerHeight: loadingContainerHeight,
        isLandscapeFormat: isLandscapeFormat,
        width: maxZoomedWidth,
        title: details.title
      }));
    }
  }]);
  return Optiondetail;
}(_react["default"].Component);
_defineProperty(Optiondetail, "swipeDelta", 50);
Optiondetail.defaultProps = {
  OptionlistitemAmount: _OptionAmount["default"],
  LoadingComponent: _LoadingOverlay["default"]
};
var _default = exports["default"] = (0, _styles.withStyles)(styles, {
  name: 'Optiondetail'
})((0, _withWidth["default"])({
  initialWidth: 'xl'
})(Optiondetail));