import _regeneratorRuntime from "@babel/runtime/regenerator";
import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import { forwardRef, useRef, useState } from 'react';
import { FormattedMessage, useIntl } from "react-intl";
import Button from "@material-ui/core/Button";
import { useMutations } from './api';
import { useSnackbar } from 'notistack';
import { makeStyles } from "@material-ui/core/styles";
import { jsx as _jsx } from "react/jsx-runtime";
var useStyles = makeStyles(function (theme) {
  return {
    button: {
      marginRight: theme.spacing(1)
    }
  };
});
export default function withDraftSave(Form) {
  return /*#__PURE__*/forwardRef(function (props, ref) {
    var _ref, _props$config, _props$config4;

    var classes = useStyles();

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

    var _useState3 = useState(props.dataIsDraft),
        _useState4 = _slicedToArray(_useState3, 2),
        isDraft = _useState4[0],
        setIsDraft = _useState4[1];

    var formRef = 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 = _slicedToArray(_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 = useIntl();

    var _useSnackbar = 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 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
        var _props$config2, _props$config3, _onSave;

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

        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                data = _objectSpread(_objectSpread({
                  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
                  },
                  values: props === null || props === void 0 ? void 0 : props.formData,
                  _id: draftId
                });
                onSave = props.onDraftSave;
                _useMutations = 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 = 8;
                  break;
                }

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

              case 8:
                _context.next = 10;
                return onSave(data, props.credentials, props.formDataAction, isDraft, props.layer);

              case 10:
                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 13:
              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__*/_jsx(Button, {
      onClick: function onClick() {
        return draftSave();
      },
      className: classes.button,
      children: /*#__PURE__*/_jsx(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__*/_jsx(Form, _objectSpread(_objectSpread({
      ref: ref
    }, props), {}, {
      dataIsDraft: isDraft,
      dataId: draftId,
      draftButton: props.draftButton ? props.draftButton : draftButton
    })) : /*#__PURE__*/_jsx(Form, _objectSpread({
      ref: ref
    }, props));
  });
}
//# sourceMappingURL=withDraftSave.js.map