import React from "react";
import ReactDOM from "react-dom";

import { CONSTANTS } from "./constants";
import Notification from "./Notification";

let wrapper = document.getElementById(CONSTANTS.PARENT_DOM_ID);

const destroyDOM = () => {
  const closeDOM = document.querySelectorAll(`.${CONSTANTS.CLOSE_ICON_CLASS}`);

  if (closeDOM && closeDOM.length > 0) {
    closeDOM.forEach(item => {
      item.click();
    });
  }

  // Wait for exit animation to complete
  setTimeout(() => {
    wrapper.innerHTML = "";
  }, 50);
};

// Use ReactDOM to render a notification
class Notify {
  send = config => {
    const autoDismiss =
      config.autoDismiss !== undefined ? config.autoDismiss : true;

    if (!wrapper) {
      wrapper = document.createElement("div");
      wrapper.id = CONSTANTS.PARENT_DOM_ID;
      document.body.appendChild(wrapper);
    }

    destroyDOM();

    // Wait till DOM is empty
    setTimeout(() => {
      const el = document.createElement("div");
      wrapper.appendChild(el);

      const destroy = () => {
        ReactDOM.unmountComponentAtNode(el);
        el.remove();
      };

      ReactDOM.render(
        <Notification
          {...config}
          onDestroy={autoDismiss || config.closeable ? destroy : null}
        />,
        el,
      );
    }, 60);
  };

  destroyAll = () => {
    destroyDOM();
  };
}

export default new Notify();
