import type { App } from "vue";
import type { ICommonRoot } from "./CommonRoot.vue";
import type { DialogAlertOptions } from "./DialogRoot.vue";
import type { ToastShowProps } from "../feedback/Toast.vue";
import type { ActionSheetOptions } from "./ActionSheetRoot.vue";

const currentRootStack : ICommonRoot[] = [];

export function setCurrentRoot(root : ICommonRoot) {
  currentRootStack.push(root);
}
export function destroyCurrentRoot(root : ICommonRoot) {
  const index = currentRootStack.indexOf(root);
  if (index !== -1)
    currentRootStack.splice(index, 1);
}
export function NaDialogRoot() : ICommonRoot {
  if (!currentRootStack.length)
    throw new Error("No dialog root found.");
  return currentRootStack[currentRootStack.length - 1];
}

export function alert(options: DialogAlertOptions) {
  return NaDialogRoot().alert(options);
}
export function confirm(options: DialogAlertOptions) {
  return NaDialogRoot().confirm(options);
}
export function toast(options: ToastShowProps|string) {
  return NaDialogRoot().toast(options);
}
export function closeToast() {
  return NaDialogRoot().closeToast();
}
export function actionSheet(options: ActionSheetOptions) {
  return NaDialogRoot().actionSheet(options);
}
export function notify(options: ToastShowProps) {
  return NaDialogRoot().notify(options);
}

let startZIndex = 1010;

export function getCurrentZIndex() {
  startZIndex += 3;
  return startZIndex;
}

export default {
  install(app: App) {
    const na : ICommonRoot = {
      alert,
      confirm,
      toast,
      closeToast,
      actionSheet,
      notify,
    }
    app.config.globalProperties.$na = na;
  }
}
