"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 _findIndex = _interopRequireDefault(require("lodash/findIndex"));
var _values = _interopRequireDefault(require("lodash/values"));
var _first = _interopRequireDefault(require("lodash/first"));
var _ComponentContainer = require("../../../../Framework/ComponentContainer");
var _i18n = require("../../../../Framework/i18n");
var _ServiceLocator = require("../../../ServiceLocator");
var _Selectors = require("../../../Reducers/DesignArea/Selectors");
var _Selectors2 = require("../../../Reducers/UI/Selectors");
var _Selectors3 = require("../../../Reducers/Configurator/Selectors");
var _CalculationWidget = _interopRequireDefault(require("../Components/CalculationWidget"));
var _Notification = _interopRequireDefault(require("../../../Shared/Components/Notification"));
var _PriceList = _interopRequireDefault(require("../../../Shared/Components/PriceList"));
var _Progress = _interopRequireDefault(require("../../../Shared/Components/Progress/Progress"));
var _TotalPrice = require("../Components/TotalPrice/TotalPrice");
var _AmountPrice = require("../../../Shared/Containers/AmountPrice");
var _Constant = require("../../../Constant");
var _configuration = require("../../../configuration");
var _createSelector = _interopRequireDefault(require("../../../../Utils/Function/createSelector"));
var _keys = _interopRequireDefault(require("lodash/keys"));
var _pickBy = _interopRequireDefault(require("lodash/pickBy"));
var _Actions = require("../../../Reducers/DesignArea/Actions");
var _Selectors4 = require("../../../Reducers/ConfigurationMode/Selectors");
var _excluded = ["containerProps"];
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 _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
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 onSelectableCalculationChange = function onSelectableCalculationChange(identifier, value) {
  return _ServiceLocator.Services.configurator.setSelectedCalculation(identifier, value);
};
var CalculationWidgetContainer = function CalculationWidgetContainer(_ref) {
  var containerProps = _ref.containerProps,
    props = _objectWithoutProperties(_ref, _excluded);
  var isLoadingPrice = containerProps.isLoadingPrice,
    isLoadingCritical = containerProps.isLoadingCritical,
    amountProps = containerProps.amountProps,
    priceProps = containerProps.priceProps,
    vatNotice = containerProps.vatNotice;
  var CalculationWidgetComponent = props.CalculationWidgetComponent,
    PriceListComponent = props.PriceListComponent,
    ProgressComponent = props.ProgressComponent,
    NotificationComponent = props.NotificationComponent,
    TotalPriceComponent = props.TotalPriceComponent;
  var error = priceProps.error;
  var errors = (0, _get["default"])(error, 'errors', []);
  var showPriceList = priceProps.priceList.length > 0;
  var defaultDesignArea = props.defaultDesignArea,
    activeDesignAreas = props.activeDesignAreas,
    toggleDesignArea = props.toggleDesignArea;
  (0, _react.useEffect)(function () {
    defaultDesignArea && (0, _findIndex["default"])((0, _values["default"])(activeDesignAreas)) === -1 && toggleDesignArea(defaultDesignArea, true);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  return /*#__PURE__*/_react["default"].createElement(CalculationWidgetComponent, _extends({
    priceListComponent: /*#__PURE__*/_react["default"].createElement("div", {
      style: {
        position: 'relative'
      }
    }, /*#__PURE__*/_react["default"].createElement(ProgressComponent, {
      loading: isLoadingPrice
    }), showPriceList && /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(PriceListComponent, {
      amount: amountProps.amount,
      list: priceProps.priceList,
      totalPrice: priceProps.priceFormatted,
      taxNote: vatNotice,
      onSelectableChanged: onSelectableCalculationChange
    }), /*#__PURE__*/_react["default"].createElement(TotalPriceComponent, {
      totalPrice: priceProps.priceFormatted,
      taxNote: vatNotice
    }))),
    loaderComponent: /*#__PURE__*/_react["default"].createElement(ProgressComponent, {
      loading: isLoadingCritical
    }),
    notificationComponent: errors.map(function (errorItem, key) {
      return /*#__PURE__*/_react["default"].createElement(NotificationComponent, {
        priceList: priceProps.priceList,
        key: key,
        icon: "error",
        color: "error",
        notification: (0, _i18n.t)('amountPrice.minimumAmountError', {
          minimumAmount: errorItem.minimumAmount,
          itemTitle: errorItem.itemTitle,
          selectedAmount: errorItem.selectedAmount
        })
      });
    })
  }, props));
};
CalculationWidgetContainer.defaultProps = {
  CalculationWidgetComponent: _CalculationWidget["default"],
  PriceListComponent: _PriceList["default"],
  ProgressComponent: _Progress["default"],
  NotificationComponent: _Notification["default"],
  TotalPriceComponent: _TotalPrice.TotalPrice,
  defaultDesignArea: null,
  activeDesignAreas: {}
};
var getSavingState = (0, _Selectors2.createBackgroundWorkStateSelector)('saveConfiguration');
var getDefaultDesignAreaIdentifier = (0, _createSelector["default"])(function (_ref2) {
  var filteredDesignAreas = _ref2.filteredDesignAreas;
  return filteredDesignAreas;
}, function (filteredDesignAreas) {
  var defaultDesignArea = null;
  if (filteredDesignAreas.length > 0) {
    defaultDesignArea = (0, _Selectors.getDefaultDesignAreaIdentifierFromProductionMethod)(_ServiceLocator.Services.store.state) || (0, _first["default"])(filteredDesignAreas).identifier;
  }
  return defaultDesignArea;
});
var mapStateToProps = function mapStateToProps(state) {
  var _getSelectedDesignAre = (0, _Selectors.getSelectedDesignAreaProperties)(state),
    filteredDesignAreas = _getSelectedDesignAre.filteredDesignAreas,
    designProductionMethod = _getSelectedDesignAre.designProductionMethod,
    selectedDesignArea = _getSelectedDesignAre.selectedDesignArea;
  var designAreas = filteredDesignAreas.map(function (da) {
    return _objectSpread(_objectSpread({}, da), {}, {
      name: da.title
    });
  });
  var designProductionMethods = (selectedDesignArea.designProductionMethods || []).map(function (dpm) {
    return _objectSpread(_objectSpread({}, dpm), {}, {
      name: dpm.title
    });
  });
  var colorAmountList = [];
  var maxColorAmount = (0, _get["default"])(designProductionMethod, 'options.maxColorAmount');
  if (maxColorAmount) {
    for (var i = 1; i <= maxColorAmount; i++) {
      colorAmountList.push({
        identifier: i,
        name: i + (i === 1 ? (0, _i18n.t)('designAreaControlbox.color') : (0, _i18n.t)('designAreaControlbox.colors'))
      });
    }
  }
  var priceProps = (0, _AmountPrice.createPricePropsFromState)(state.configurator);
  var amountProps = (0, _AmountPrice.createAmountPropsFromState)(state.configurator);
  var isLoadingPrice = (0, _get["default"])(state.api, 'sources.calculation.isFetching', false);
  var isInitialLoadingInProgress = !(0, _Selectors3.getItem)(state.configurator).identifier && state.api.isFetching;
  var isLoadingCritical = getSavingState(state.ui) || isInitialLoadingInProgress;
  var isSaveButtonEnabled = (0, _Selectors4.isConfigurationModeAvailable)(state) && !isLoadingPrice && !priceProps.error;
  var activeDesignAreas = (0, _Selectors.getActiveDesignAreas)(state);
  var colorAmounts = (0, _Selectors.getDesignDataColorAmounts)(state);
  var vatNotice = !(0, _configuration.getConf)('displayNetPrices', false) ? (0, _i18n.t)('amountPrice.vatNotice') : (0, _i18n.t)('amountPrice.vatNoticeNet');
  var defaultDesignArea = getDefaultDesignAreaIdentifier(state.designArea);
  var hasGlobalErrors = (0, _get["default"])(state, 'ui.error');
  return {
    Component: defaultDesignArea || hasGlobalErrors ? CalculationWidgetContainer : function () {
      return null;
    },
    containerProps: {
      isLoadingPrice: isLoadingPrice,
      amountProps: amountProps,
      priceProps: priceProps,
      isLoadingCritical: isLoadingCritical,
      vatNotice: vatNotice
    },
    colorAmountList: colorAmountList,
    designProductionMethods: designProductionMethods,
    amountValue: amountProps.amount,
    designAreas: designAreas,
    currentDesignProductionMethod: designProductionMethod,
    colorAmounts: colorAmounts,
    selectedDesignArea: selectedDesignArea,
    isSaveButtonEnabled: isSaveButtonEnabled,
    activeDesignAreas: activeDesignAreas,
    defaultDesignArea: defaultDesignArea
  };
};
var mapDispatchToProps = function mapDispatchToProps() {
  return {
    onChangeAmount: function onChangeAmount(amount) {
      _ServiceLocator.Services.configurator.skipNextCalculationAutoResolve();
      _ServiceLocator.Services.configurator.setSelectedAmount(false, amount);
    },
    handleChangeDesignArea: function handleChangeDesignArea(identifier) {
      return _ServiceLocator.Services.store.dispatch((0, _Actions.selectDesignArea)(identifier));
    },
    handleChangeDesignProductionMethod: function handleChangeDesignProductionMethod(identifier) {
      _ServiceLocator.Services.designData.setDesignProductionMethod(identifier);
    },
    handleChangeSelectedColorAmount: function handleChangeSelectedColorAmount(designAreaIdentifier, value) {
      _ServiceLocator.Services.designData.getSampleCanvasEditorForDesignArea(designAreaIdentifier).setColorAmount(value);
    },
    toggleDesignArea: function toggleDesignArea(designAreaIdentifier, active) {
      _ServiceLocator.Services.designData.getSampleCanvasEditorForDesignArea(designAreaIdentifier).toggleSampleText(active);
      _ServiceLocator.Services.analytics.triggerEvent(active ? _Constant.EventTypes.widget_add_design_area : _Constant.EventTypes.widget_remove_design_area, designAreaIdentifier);
    },
    addPlaceholderImage: function addPlaceholderImage(active) {
      var designAreaIdentifiers = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (0, _keys["default"])((0, _pickBy["default"])((0, _Selectors.getActiveDesignAreas)(_ServiceLocator.Services.store.state)));
      _ServiceLocator.Services.designData.addSampleImageForDesignAreas(designAreaIdentifiers, active);
    },
    onClickSaveConfiguration: function onClickSaveConfiguration() {
      return _ServiceLocator.Services.interaction.saveWidgetConfigurationAndOpenConfigurator();
    },
    onClickPrintConfiguration: function onClickPrintConfiguration() {
      return _ServiceLocator.Services.interaction.saveWidgetConfigurationAndOpenPdf();
    }
  };
};
var _default = exports["default"] = (0, _ComponentContainer.containerConnect)(mapStateToProps, mapDispatchToProps);