<script setup>
import { shallowReactive, onMounted } from "vue";
import { useDialog } from "../../composables/dialog";
const dialogs = shallowReactive([]);
let idCounter = 0;
function open(component, inputProps = {}) {
  const id = ++idCounter;
  const promise = new Promise((resolve, reject) => {
    const dialogProps = {
      ...inputProps,
      modelValue: true,
      "onUpdate:modelValue": (v) => {
        if (!v) close(id, null);
      },
      onResolve: (val) => close(id, val),
      onReject: (val) => closeWithReject(id, val)
    };
    dialogs.push({
      id,
      component,
      props: dialogProps,
      resolve,
      reject
    });
  });
  const closeInstance = (val) => {
    close(id, val);
  };
  const rejectInstance = (val) => {
    closeWithReject(id, val);
  };
  return { id, promise, closeInstance, rejectInstance };
}
function close(id, val) {
  const index = dialogs.findIndex((d) => d.id === id);
  if (index !== -1) {
    dialogs[index].resolve(val);
    dialogs.splice(index, 1);
  }
}
function closeWithReject(id, val) {
  const index = dialogs.findIndex((d) => d.id === id);
  if (index !== -1) {
    dialogs[index].reject(val);
    dialogs.splice(index, 1);
  }
}
onMounted(() => {
  useDialog()?.setDialogHost(open, close);
});
defineExpose({ open, close });
</script>

<template>
  <Teleport to="body">
    <div>
      <component
          v-for="dialog in dialogs"
          :key="dialog.id"
          :is="dialog.component"
          v-bind="dialog.props"
      />
    </div>
  </Teleport>
</template>
