import * as React from 'react';
import * as ReactDOM from 'react-dom';

export default function modalOpen<T>(config: T, Componet) {
  const div = document.createElement('div');
  document.body.appendChild(div);

  let currentConfig = {
    ...config,
    onCancel: () => {
      if ((config as any).onCancel) {
        (config as any).onCancel();
      }
      close();
    },
    visible: true,
  } as any;

  function destroy() {
    const unmountResult = ReactDOM.unmountComponentAtNode(div);
    if (unmountResult && div.parentNode) div.parentNode.removeChild(div);
  }

  function close(this: any) {
    currentConfig = {
      ...currentConfig,
      visible: false,
      afterClose: destroy.bind(this),
    };
    render(currentConfig);
  }

  function render(props) {
    ReactDOM.render(<Componet {...props} />, div);
  }

  render(currentConfig);

  return {};
}
