import { createApp } from "vue";
import {
  defaultModalContainerId,
  modalService,
  InklineKey,
  InklineModalKey,
  modalEventBus
} from "@inkline/inkline/constants";
import { IModalContainer } from "@inkline/inkline/components/IModalContainer";
import { IconsPlugin } from "@inkline/inkline/plugins/icons";
export const ModalPlugin = {
  install: (app, { inkline }) => {
    app.config.globalProperties.$modal = modalService;
    app.provide(InklineModalKey, modalService);
    if (typeof window === "undefined") {
      return;
    }
    const containerId = defaultModalContainerId;
    const containerDataAttrbiute = `data-${containerId}`;
    let container = document.querySelector(`#${containerId}`);
    if (!container) {
      container = document.createElement("div");
      container.id = containerId;
      document.body.appendChild(container);
    }
    if (!container.hasAttribute(containerDataAttrbiute)) {
      const modalApp = createApp(IModalContainer, {
        eventBus: modalEventBus
      });
      modalApp.provide(InklineKey, inkline);
      modalApp.use(IconsPlugin);
      container.setAttribute(containerDataAttrbiute, "");
      modalApp.mount(container);
    }
  }
};
