import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import React from 'react';
import ReactDOM from 'react-dom';
import ModalRenderFunction from './modalFunctionComp';
import ActionModal from './actionsModal';
import { tuple } from '../utils/tuple';
import destroyFnsSet from './destroyFns';
var ActionsTuple = tuple('info', 'success', 'warning', 'error');
var modal_global_config = {};

function open(config) {
  var div = document.createElement('div');
  document.body.appendChild(div);

  var currentConfig = _objectSpread(_objectSpread({}, config), {}, {
    visible: true,
    closeModal: closeModal
  });

  function destoryModal() {
    var unmountResult = ReactDOM.unmountComponentAtNode(div);

    if (unmountResult && div.parentNode) {
      div.parentNode.removeChild(div);
    }
  }

  if (!destroyFnsSet.has(destoryModal)) {
    destroyFnsSet.add(destoryModal);
  }

  function renderModal(modalConfig) {
    var endModalConfig = _objectSpread({
      getContainer: modal_global_config.getContainer
    }, modalConfig);

    setTimeout(function () {
      ReactDOM.render( /*#__PURE__*/React.createElement(ActionModal, Object.assign({}, endModalConfig)), div);
    });
  }

  function closeModal() {
    currentConfig = _objectSpread(_objectSpread({}, currentConfig), {}, {
      visible: false,
      afterClose: function afterClose() {
        if (typeof config.afterClose === 'function') {
          config.afterClose();
        }

        destoryModal();

        if (destroyFnsSet.has(destoryModal)) {
          destroyFnsSet.delete(destoryModal);
        }
      }
    });
    renderModal(currentConfig);
  }

  function update(updateConfig) {
    if (typeof updateConfig === 'function') {
      currentConfig = updateConfig(currentConfig);
    } else {
      currentConfig = _objectSpread(_objectSpread({}, currentConfig), updateConfig);
    }

    renderModal(currentConfig);
  }

  renderModal(currentConfig);
  return {
    destroy: closeModal,
    update: update
  };
}

var Modal = ModalRenderFunction;

Modal.config = function (globalProps) {
  modal_global_config.getContainer = globalProps.getContainer;
};

Modal.destroyAll = function () {
  destroyFnsSet.forEach(function (fn) {
    return fn === null || fn === void 0 ? void 0 : fn();
  });
  destroyFnsSet.clear();
};

ActionsTuple.forEach(function (action) {
  Modal[action] = function (config) {
    return open(_objectSpread({
      type: action
    }, config));
  };
});
export default Modal;