"use strict";

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

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

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

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

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

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

var _react = require("react");

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

var _Button = _interopRequireDefault(require("@material-ui/core/Button"));

var _api = require("./api");

var _ConfirmDialog = _interopRequireDefault(require("./ConfirmDialog"));

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

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

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

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

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

var _excluded = ["formMetaData", "onPreSubmit", "onPostSubmit", "formDataAction", "credentials", "credentialsCallback", "dataIsDraft", "customMessages", "layer"];
var useStyles = (0, _styles.makeStyles)(function (theme) {
  return {
    noPrint: {
      '& > *': {
        '@media print': {
          display: 'none'
        }
      }
    }
  };
});

function withConfirmSubmit(Form) {
  return /*#__PURE__*/(0, _react.forwardRef)(function (_ref, ref) {
    var _customMessages$confi, _customMessages$submi;

    var formMetaData = _ref.formMetaData,
        onPreSubmit = _ref.onPreSubmit,
        onPostSubmit = _ref.onPostSubmit,
        formDataAction = _ref.formDataAction,
        credentials = _ref.credentials,
        credentialsCallback = _ref.credentialsCallback,
        dataIsDraft = _ref.dataIsDraft,
        customMessages = _ref.customMessages,
        layer = _ref.layer,
        otherProps = (0, _objectWithoutProperties2["default"])(_ref, _excluded);

    var _useMutations = (0, _api.useMutations)(),
        submit = _useMutations.submit;

    var config = otherProps.config,
        _otherProps$onSubmit = otherProps.onSubmit,
        onSubmit = _otherProps$onSubmit === void 0 ? submit : _otherProps$onSubmit;
    var meta = config.meta;
    var confirmDialogRef = (0, _react.useRef)();
    var containerRef = (0, _react.useRef)();
    var classes = useStyles();
    var intl = (0, _reactIntl.useIntl)();
    var locale = intl.locale;
    var hasConfirmValue = (0, _customizations.hasConfirm)(otherProps);
    var dialogTitle = (_customMessages$confi = customMessages === null || customMessages === void 0 ? void 0 : customMessages.confirmDialogTitle) !== null && _customMessages$confi !== void 0 ? _customMessages$confi : (meta === null || meta === void 0 ? void 0 : meta.preview) ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactIntl.FormattedMessage, {
      id: "2bIMAQ",
      defaultMessage: [{
        "type": 0,
        "value": "Tarkista ja lähetä lomake"
      }]
    }) : (meta === null || meta === void 0 ? void 0 : meta.consent) ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactIntl.FormattedMessage, {
      id: "iO1LSB",
      defaultMessage: [{
        "type": 0,
        "value": "Vahvista ja lähetä lomake"
      }]
    }) : /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactIntl.FormattedMessage, {
      id: "90nFnm",
      defaultMessage: [{
        "type": 0,
        "value": "Lähetä lomake"
      }]
    });
    return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
      children: [hasConfirmValue && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
          ref: containerRef
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_ConfirmDialog["default"], (0, _objectSpread2["default"])({
          title: dialogTitle,
          ref: confirmDialogRef,
          customMessages: customMessages,
          container: containerRef.current
        }, otherProps))]
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, (0, _core.useMediaQuery)('print') && (0, _customizations.hasPreview)(otherProps) ? {
        className: classes.noPrint
      } : {}), {}, {
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(Form, (0, _objectSpread2["default"])((0, _objectSpread2["default"])({
          ref: ref,
          credentials: credentials,
          credentialsCallback: credentialsCallback,
          formDataAction: formDataAction,
          dataIsDraft: dataIsDraft,
          customMessages: customMessages,
          layer: layer
        }, otherProps), {}, {
          onSubmit: (0, _utils.chain)([onPreSubmit, hasConfirmValue && function () {
            var _confirmDialogRef$cur;

            return (_confirmDialogRef$cur = confirmDialogRef.current).confirm.apply(_confirmDialogRef$cur, arguments);
          }, hasConfirmValue && function () {
            confirmDialogRef.current.loading();

            for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
              args[_key] = arguments[_key];
            }

            return args;
          }, /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
            var _len2,
                args,
                _key2,
                _args$,
                captchaChallenge,
                formData,
                data,
                callbackCredentials,
                response,
                _e$response,
                _args = arguments;

            return _regenerator["default"].wrap(function _callee$(_context) {
              while (1) {
                switch (_context.prev = _context.next) {
                  case 0:
                    for (_len2 = _args.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
                      args[_key2] = _args[_key2];
                    }

                    _args$ = args[0], captchaChallenge = _args$.captchaChallenge, formData = _args$.formData;
                    data = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({
                      status: 'SUBMITTED',
                      form: {
                        id: config._id,
                        rev: config._rev,
                        lang: locale.split('-')[0]
                      }
                    }, formMetaData), {}, {
                      values: formData,
                      captchaChallenge: captchaChallenge,
                      _id: otherProps.dataId
                    });
                    _context.prev = 3;

                    if (!credentialsCallback) {
                      _context.next = 10;
                      break;
                    }

                    _context.next = 7;
                    return credentialsCallback();

                  case 7:
                    _context.t0 = _context.sent;
                    _context.next = 11;
                    break;

                  case 10:
                    _context.t0 = credentials;

                  case 11:
                    callbackCredentials = _context.t0;
                    _context.next = 14;
                    return onSubmit.apply(void 0, [data, callbackCredentials, formDataAction, dataIsDraft, layer].concat(args));

                  case 14:
                    response = _context.sent;

                    if (hasConfirmValue) {
                      confirmDialogRef.current.close();
                    }

                    onPostSubmit === null || onPostSubmit === void 0 ? void 0 : onPostSubmit.apply(void 0, [response, data].concat(args));
                    _context.next = 23;
                    break;

                  case 19:
                    _context.prev = 19;
                    _context.t1 = _context["catch"](3);
                    console.error(_context.t1);

                    if (hasConfirmValue) {
                      confirmDialogRef.current.error((_e$response = _context.t1.response) === null || _e$response === void 0 ? void 0 : _e$response.data);
                    }

                  case 23:
                  case "end":
                    return _context.stop();
                }
              }
            }, _callee, null, [[3, 19]]);
          }))]),
          children: otherProps.children ? otherProps.children : /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
            children: [otherProps.draftButton, /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button["default"], {
              type: "submit",
              variant: "contained",
              color: "primary",
              children: (_customMessages$submi = customMessages === null || customMessages === void 0 ? void 0 : customMessages.submit) !== null && _customMessages$submi !== void 0 ? _customMessages$submi : /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactIntl.FormattedMessage, {
                id: "6jFMKd",
                defaultMessage: [{
                  "type": 0,
                  "value": "Lähetä"
                }]
              })
            })]
          })
        }))
      }))]
    });
  });
}
//# sourceMappingURL=withConfirmSubmit.cjs.map