"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));

var _core = require("@material-ui/core");

var _lab = require("@material-ui/lab");

var _immer = _interopRequireDefault(require("immer"));

var _react = require("react");

var _reactIntl = require("react-intl");

var _customizations = require("./customizations");

var _PrintButton = require("./PrintButton");

var _Field = _interopRequireDefault(require("./Review/Field"));

var _utils = require("./utils");

var _reactGoogleRecaptchaV = require("react-google-recaptcha-v3");

var _jsxRuntime = require("react/jsx-runtime");

var _excluded = ["container", "title", "description", "children", "onConfirm", "confirmComponent", "customMessages", "onCloseDialog"];
var sendErrorMessages = {
  10: (0, _reactIntl.defineMessage)({
    id: "AqWjHF",
    defaultMessage: [{
      "type": 0,
      "value": "Lomakkeen lähetys ei onnistunut."
    }]
  }),
  40: (0, _reactIntl.defineMessage)({
    id: "ylKM8r",
    defaultMessage: [{
      "type": 0,
      "value": "Lomakkeen lähetys ei onnistunut, koska liitetiedostojen virustarkistus epäonnistui."
    }]
  }),
  50: (0, _reactIntl.defineMessage)({
    id: "2T0Ypn",
    defaultMessage: [{
      "type": 0,
      "value": "Lomakkeen lähetys ei onnistunut, koska captchatarkistus epäonnistui."
    }]
  })
};

var _default = /*#__PURE__*/(0, _react.forwardRef)(function ConfirmDialog(_ref, ref) {
  var _otherProps$config, _customMessages$confi, _customMessages$confi2, _customMessages$confi3, _customMessages$confi4;

  var container = _ref.container,
      title = _ref.title,
      description = _ref.description,
      children = _ref.children,
      onConfirm = _ref.onConfirm,
      confirmComponent = _ref.confirmComponent,
      customMessages = _ref.customMessages,
      onCloseDialog = _ref.onCloseDialog,
      otherProps = (0, _objectWithoutProperties2["default"])(_ref, _excluded);
  (0, _react.useImperativeHandle)(ref, function () {
    return {
      confirm: function confirm() {
        for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
          args[_key] = arguments[_key];
        }

        return new Promise(function (resolve) {
          confirmRef.current = function (confirm) {
            resolve((0, _customizations.hasCaptcha)(otherProps) ? confirm && (0, _immer["default"])(args, function (_ref2) {
              var _ref3 = (0, _slicedToArray2["default"])(_ref2, 1),
                  data = _ref3[0];

              data.captchaChallenge = confirm;
            }) : confirm);
          };

          setOpen(true);
        });
      },
      loading: function loading() {
        handleLoading();
      },
      close: function close() {
        handleClose();
      },
      error: function error(data) {
        handleError(data);
      }
    };
  }); // const dialogContentFlexNoneClasses = useStylesDialogContentFlexNone();

  var pageTitlesArray = otherProps === null || otherProps === void 0 ? void 0 : (_otherProps$config = otherProps.config) === null || _otherProps$config === void 0 ? void 0 : _otherProps$config.elements.filter(function (x) {
    return x.type === 'pageTitle' && x.content;
  });
  var confirmRef = (0, _react.useRef)();
  var hasCaptchaValue = (0, _customizations.hasCaptcha)(otherProps);
  var hasConsentValue = (0, _customizations.hasConsent)(otherProps);

  var _useState = (0, _react.useState)(false),
      _useState2 = (0, _slicedToArray2["default"])(_useState, 2),
      open = _useState2[0],
      setOpen = _useState2[1];

  var _useState3 = (0, _react.useState)(false),
      _useState4 = (0, _slicedToArray2["default"])(_useState3, 2),
      loading = _useState4[0],
      setLoading = _useState4[1];

  var _useState5 = (0, _react.useState)(null),
      _useState6 = (0, _slicedToArray2["default"])(_useState5, 2),
      error = _useState6[0],
      setError = _useState6[1];

  var _useState7 = (0, _react.useState)(false),
      _useState8 = (0, _slicedToArray2["default"])(_useState7, 2),
      consent = _useState8[0],
      setConsent = _useState8[1];

  var intl = (0, _reactIntl.useIntl)();

  var _useGoogleReCaptcha = (0, _reactGoogleRecaptchaV.useGoogleReCaptcha)(),
      executeRecaptcha = _useGoogleReCaptcha.executeRecaptcha;

  function handleClose() {
    setLoading(false);
    setError(false);
    setOpen(false);
    onCloseDialog === null || onCloseDialog === void 0 ? void 0 : onCloseDialog();
  }

  function handleDismiss() {
    if (!loading || error) {
      setLoading(false);
      setError(null);
      handleClose();
      confirmRef.current(false);
    }
  }

  function handleLoading() {
    setLoading(true);
  }

  function handleError(data) {
    setError(sendErrorMessages[data.errorCode] ? intl.formatMessage(sendErrorMessages[data.errorCode]) : data.message);
    setLoading(false);
  }

  function handleConfirm() {
    return _handleConfirm.apply(this, arguments);
  }

  function _handleConfirm() {
    _handleConfirm = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
      var token;
      return _regenerator["default"].wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              if (!hasCaptchaValue) {
                _context.next = 7;
                break;
              }

              _context.next = 3;
              return executeRecaptcha('submit');

            case 3:
              token = _context.sent;
              confirmRef.current(token);
              _context.next = 8;
              break;

            case 7:
              confirmRef.current(true);

            case 8:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));
    return _handleConfirm.apply(this, arguments);
  }

  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_utils.Customize, (0, _objectSpread2["default"])((0, _objectSpread2["default"])({
    customizer: confirmComponent
  }, otherProps), {}, {
    children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_core.Dialog, {
      scroll: "body",
      open: open,
      onClose: handleDismiss,
      "aria-labelledby": "confirm-dialog-title",
      "aria-describedby": "confirm-dialog-description",
      fullScreen: (0, _core.useMediaQuery)('print'),
      container: container,
      disableBackdropClick: true,
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_core.DialogTitle, {
        id: "confirm-dialog-title",
        children: title
      }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_core.DialogContent, {
        children: [description && /*#__PURE__*/(0, _jsxRuntime.jsx)(_core.DialogContentText, {
          id: "confirm-dialog-description",
          children: description
        }), (0, _customizations.hasPreview)(otherProps) && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_core.Typography, {
            variant: "subtitle1",
            component: "h3",
            children: (_customMessages$confi = customMessages === null || customMessages === void 0 ? void 0 : customMessages.confirmDialogPreview) !== null && _customMessages$confi !== void 0 ? _customMessages$confi : /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactIntl.FormattedMessage, {
              id: "gkQhRC",
              defaultMessage: [{
                "type": 0,
                "value": "Lähetettävien tietojen esikatselu"
              }]
            })
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Field["default"], (0, _objectSpread2["default"])({
            preview: true // For selecting optional preview / review customization
            ,
            root: true,
            pageTitles: pageTitlesArray
          }, otherProps))]
        }), hasConsentValue && /*#__PURE__*/(0, _jsxRuntime.jsx)(_core.FormControlLabel, {
          control: /*#__PURE__*/(0, _jsxRuntime.jsx)(_core.Checkbox, {
            checked: consent,
            onChange: function onChange(event) {
              setConsent(event.target.checked);
            },
            name: "consent",
            color: "secondary"
          }),
          label: (_customMessages$confi2 = customMessages === null || customMessages === void 0 ? void 0 : customMessages.confirmDialogConsent) !== null && _customMessages$confi2 !== void 0 ? _customMessages$confi2 : intl.formatMessage({
            id: "BFjxIc",
            defaultMessage: [{
              "type": 0,
              "value": "Vahvistan ilmoitetut tiedot oikeiksi"
            }]
          })
        }, "consent"), loading && /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_core.CircularProgress, {})
        }), error && /*#__PURE__*/(0, _jsxRuntime.jsx)(_core.DialogContentText, {
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_lab.Alert, {
            severity: "error",
            children: error
          })
        })]
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_core.Box, {
        displayPrint: "none",
        children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_core.DialogActions, {
          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_core.Button, {
            disabled: loading && !error,
            onClick: handleDismiss,
            children: (_customMessages$confi3 = customMessages === null || customMessages === void 0 ? void 0 : customMessages.confirmDialogCancelButton) !== null && _customMessages$confi3 !== void 0 ? _customMessages$confi3 : /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactIntl.FormattedMessage, {
              id: "/FfZeC",
              defaultMessage: [{
                "type": 0,
                "value": "Peruuta"
              }]
            })
          }), (0, _customizations.hasPreview)(otherProps) && (0, _customizations.hasPrint)(otherProps) && /*#__PURE__*/(0, _jsxRuntime.jsx)(_PrintButton.PrintButton, {}), /*#__PURE__*/(0, _jsxRuntime.jsx)(_core.Button, {
            disabled: hasConsentValue && !consent || loading || error || !loading && hasCaptchaValue && !executeRecaptcha,
            onClick: handleConfirm,
            variant: "contained",
            color: "primary",
            autoFocus: true,
            children: (_customMessages$confi4 = customMessages === null || customMessages === void 0 ? void 0 : customMessages.confirmDialogSendButton) !== null && _customMessages$confi4 !== void 0 ? _customMessages$confi4 : /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactIntl.FormattedMessage, {
              id: "6jFMKd",
              defaultMessage: [{
                "type": 0,
                "value": "Lähetä"
              }]
            })
          })]
        })
      })]
    })
  }));
});

exports["default"] = _default;
//# sourceMappingURL=ConfirmDialog.cjs.map