"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.exportStateMiddleware = void 0;
var _stringifyJSON = require("../utils/stringifyJSON");
var _actionTypes = require("../constants/actionTypes");
var _instances = require("../reducers/instances");
let toExport;
function download(state) {
  const blob = new Blob([state], {
    type: 'octet/stream'
  });
  const href = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.style.display = 'none';
  a.download = 'state.json';
  a.href = href;
  document.body.appendChild(a);
  a.click();
  setTimeout(() => {
    document.body.removeChild(a);
    window.URL.revokeObjectURL(href);
  }, 0);
}
const exportStateMiddleware = store => next => action => {
  const result = next(action);
  if (toExport && action.type === _actionTypes.UPDATE_STATE && action.request.type === 'EXPORT') {
    const request = action.request;
    const id = request.instanceId || request.id;
    if (id === toExport) {
      toExport = undefined;
      download(JSON.stringify({
        payload: request.payload,
        preloadedState: request.committedState
      }, null, '\t'));
    }
  } else if (action.type === _actionTypes.EXPORT) {
    const instances = store.getState().instances;
    const instanceId = (0, _instances.getActiveInstance)(instances);
    const options = instances.options[instanceId];
    if (options.features.export === true) {
      download((0, _stringifyJSON.stringifyJSON)(instances.states[instanceId], options.serialize));
    } else {
      toExport = instanceId;
      next({
        type: _actionTypes.LIFTED_ACTION,
        message: 'EXPORT',
        toExport: true
      });
    }
  }
  return result;
};
exports.exportStateMiddleware = exportStateMiddleware;