// @ts-nocheck

import Dialog from './Dialog.vue';
import Window from './Window.vue';
import Toast from './Toast.vue';
import Alert from './Alert.vue';
import Confirm from './Confirm.vue';
import DialogContent from './Dialog-content.vue';
import { createVNode, render } from 'vue';

function mount(component, { props, children, element, app } = {}) {
  let el = element;
  let vNode = createVNode(component, props, children);

  if (app && app._context) vNode.appContext = app._context;
  if (el) render(vNode, el);
  else if (typeof document !== 'undefined') {
    render(vNode, (el = document.createElement('div')));
  }

  const destroy = () => {
    if (el) render(null, el);
    el = null;
    vNode = null;
  };

  return { vNode, destroy, el };
}
// const Dialog =window

Dialog.use = function use(app) {
  Dialog.toast = function (options) {
    if (typeof options == 'string') {
      options = {
        content: options,
      };
    }

    const { destroy, vNode, el } = mount(Toast, {
      app,
      props: { ...options, destroy: () => destroy() },
    });

    if (!Dialog.toast._destroys) {
      Dialog.toast._destroys = [];
    }
    Dialog.toast._destroys.push(destroy);

    return {
      hide: function () {
        let destroy = null;
        while ((destroy = Dialog.toast._destroys.shift()) && destroy) {
          destroy();
        }
      }.bind(this),
    };
  };
  Dialog.toast.hide = function () {
    if (Dialog.toast._destroys && Dialog.toast._destroys.length) {
      const destroy = Dialog.toast._destroys.pop();
      destroy && destroy();
    }
  };
  Dialog.alert = function (options) {
    if (typeof options == 'string') {
      options = {
        content: options,
      };
    }

    const { destroy } = mount(Alert, {
      app,
      props: { ...options, destroy: () => destroy() },
    });

    this.alert.hide = function () {
      destroy();
    };

    return this.alert;
  };

  Dialog.confirm = function (options) {
    if (typeof options == 'string') {
      options = {
        content: options,
      };
    }

    let promise;
    if (!options.func) {
      promise = new Promise((resolve) => {
        options.func = (result) => resolve(result === 'ok');
      });
    }

    const { destroy } = mount(Confirm, {
      app,
      props: { ...options, destroy: () => destroy() },
    });

    this.confirm.hide = function () {
      destroy();
    };

    return promise || this.confirm;
  };
};
// console.log('Dialog', Dialog)

export { Window, Toast, Alert, Confirm, DialogContent };

export default Dialog;
