"use strict";

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

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

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 _react = require("react");

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

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

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

var _notistack = require("notistack");

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

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

var useStyles = (0, _styles.makeStyles)(function (theme) {
  return {
    button: {
      marginRight: theme.spacing(1)
    }
  };
});

function withDraftSave(Form) {
  return /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
    var _ref, _props$config, _props$customMessages, _props$customMessages2, _props$config4;

    var classes = useStyles();

    var _useState = (0, _react.useState)(props.dataId && props.dataIsDraft ? props.dataId : null),
        _useState2 = (0, _slicedToArray2["default"])(_useState, 2),
        draftId = _useState2[0],
        setDraftId = _useState2[1];

    var _useState3 = (0, _react.useState)(props.dataIsDraft),
        _useState4 = (0, _slicedToArray2["default"])(_useState3, 2),
        isDraft = _useState4[0],
        setIsDraft = _useState4[1];

    var formRef = (0, _react.useRef)();
    (_ref = ref) !== null && _ref !== void 0 ? _ref : ref = formRef;

    var determineActiveStep = function determineActiveStep() {
      var _formRef$current, _formRef$current$prop;

      var newUiSchema = Object.entries(formRef === null || formRef === void 0 ? void 0 : (_formRef$current = formRef.current) === null || _formRef$current === void 0 ? void 0 : (_formRef$current$prop = _formRef$current.props) === null || _formRef$current$prop === void 0 ? void 0 : _formRef$current$prop.uiSchema).filter(function (_ref2) {
        var _ref3 = (0, _slicedToArray2["default"])(_ref2, 2),
            key = _ref3[0],
            value = _ref3[1];

        return value && value['ui:widget'] !== 'hidden';
      });
      var pageTitles = formRef.current.props.uiSchema['ui:options'].element.elements.filter(function (x) {
        return x.type === 'pageTitle';
      });
      var uiOptions = newUiSchema.pop()[1].element.elements;
      var index = uiOptions.findIndex(function (x) {
        return x.key === newUiSchema[0][0].toString();
      });

      var _loop = function _loop(i) {
        if (uiOptions[i].type === 'pageTitle') {
          return {
            v: pageTitles.findIndex(function (x) {
              return x.key === uiOptions[i].key;
            })
          };
        }
      };

      for (var i = index - 1; i >= 0; i--) {
        var _ret = _loop(i);

        if (typeof _ret === "object") return _ret.v;
      }
    };

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

    var _useSnackbar = (0, _notistack.useSnackbar)(),
        enqueueSnackbar = _useSnackbar.enqueueSnackbar;

    var multiPageForm = (props === null || props === void 0 ? void 0 : (_props$config = props.config) === null || _props$config === void 0 ? void 0 : _props$config.elements.find(function (element) {
      return element.type === 'pageTitle';
    })) ? true : false;

    var draftSave = /*#__PURE__*/function () {
      var _ref4 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
        var _props$config2, _props$config3, _onSave;

        var callbackCredentials, data, onSave, _useMutations, submit, preResult, response, _response$attributes;

        return _regenerator["default"].wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                if (!props.credentialsCallback) {
                  _context.next = 6;
                  break;
                }

                _context.next = 3;
                return props.credentialsCallback();

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

              case 6:
                _context.t0 = props.credentials;

              case 7:
                callbackCredentials = _context.t0;
                data = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({
                  status: 'DRAFT'
                }, multiPageForm && {
                  activeStep: determineActiveStep()
                }), {}, {
                  form: {
                    id: props === null || props === void 0 ? void 0 : (_props$config2 = props.config) === null || _props$config2 === void 0 ? void 0 : _props$config2._id,
                    rev: props === null || props === void 0 ? void 0 : (_props$config3 = props.config) === null || _props$config3 === void 0 ? void 0 : _props$config3._rev
                  },
                  credentials: callbackCredentials,
                  values: props === null || props === void 0 ? void 0 : props.formData,
                  _id: draftId
                });
                onSave = props.onDraftSave;
                _useMutations = (0, _api.useMutations)(), submit = _useMutations.submit;
                (_onSave = onSave) !== null && _onSave !== void 0 ? _onSave : onSave = submit;
                preResult = true;

                if (props.preDraftSave) {
                  preResult = props.preDraftSave();
                }

                if (preResult) {
                  _context.next = 16;
                  break;
                }

                return _context.abrupt("return", false);

              case 16:
                _context.next = 18;
                return onSave(data, callbackCredentials, props.formDataAction, isDraft, props.layer);

              case 18:
                response = _context.sent;

                if (response) {
                  enqueueSnackbar(intl.formatMessage({
                    id: "hc0p+s",
                    defaultMessage: [{
                      "type": 0,
                      "value": "Tallennettu"
                    }]
                  }), {
                    variant: 'success'
                  });
                  setDraftId((_response$attributes = response.attributes) === null || _response$attributes === void 0 ? void 0 : _response$attributes.id);
                  setIsDraft(true);

                  if (props.afterDraftSave) {
                    props.afterDraftSave(response);
                  }
                }

                return _context.abrupt("return", false);

              case 21:
              case "end":
                return _context.stop();
            }
          }
        }, _callee);
      }));

      return function draftSave() {
        return _ref4.apply(this, arguments);
      };
    }();

    var isSubmittedData = (props === null || props === void 0 ? void 0 : props.dataId) && !(props === null || props === void 0 ? void 0 : props.dataIsDraft);
    var draftButton = /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button["default"], {
      onClick: function onClick() {
        return draftSave();
      },
      className: classes.button,
      children: (_props$customMessages = (_props$customMessages2 = props.customMessages) === null || _props$customMessages2 === void 0 ? void 0 : _props$customMessages2.draftSave) !== null && _props$customMessages !== void 0 ? _props$customMessages : /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactIntl.FormattedMessage, {
        id: "riHrtl",
        defaultMessage: [{
          "type": 0,
          "value": "Tallenna"
        }]
      })
    });
    return (props === null || props === void 0 ? void 0 : (_props$config4 = props.config) === null || _props$config4 === void 0 ? void 0 : _props$config4.draftSave) && !isSubmittedData ? /*#__PURE__*/(0, _jsxRuntime.jsx)(Form, (0, _objectSpread2["default"])((0, _objectSpread2["default"])({
      ref: ref
    }, props), {}, {
      dataIsDraft: isDraft,
      dataId: draftId,
      draftButton: props.draftButton ? props.draftButton : draftButton
    })) : /*#__PURE__*/(0, _jsxRuntime.jsx)(Form, (0, _objectSpread2["default"])({
      ref: ref
    }, props));
  });
}
//# sourceMappingURL=withDraftSave.cjs.map