<template>
  <Dialog 
    v-bind="options"
    :show="show"
    :showConfirm="showConfirm"
    :showCancel="showCancel"
  />
</template>

<script setup lang="ts">
import { ref } from 'vue';
import Dialog, { type DialogProps } from './Dialog.vue';

export interface DialogAlertOptions extends Omit<DialogProps, 'show'> {
}
export interface DialogAlertRoot {
  confirm(options: DialogAlertOptions): Promise<boolean>;
  alert(options: DialogAlertOptions): Promise<string|undefined>;
}

const show = ref(false);
const showCancel = ref(false);
const showConfirm = ref(true);
const options = ref<DialogAlertOptions>();

defineExpose<DialogAlertRoot>({
  confirm(_options: DialogAlertOptions) {
    showCancel.value = true;

    const onConfirm = _options.onConfirm;
    const onCancel = _options.onCancel;
    
    return new Promise<boolean>((resolve) => {
      (_options as any).onClose = () => {
        show.value = false;
        resolve(false);
      };
      _options.onCancel = () => {
        show.value = false;
        onCancel?.();
        resolve(false);
      };
      _options.onConfirm = () => {
        show.value = false;
        onConfirm?.();
        resolve(true);
      };
      options.value = _options;
      show.value = true;
    });
  },
  alert(_options: DialogAlertOptions) {
    showCancel.value = false;
    show.value = true;
    options.value = _options;

    const onConfirm = _options.onConfirm;

    return new Promise<string|undefined>((resolve) => {
      (_options as any).onClose = () => {
        show.value = false;
        resolve(undefined);
      };
      _options.onConfirm = (buttonName?: string) => {
        show.value = false;
        onConfirm?.();
        resolve(buttonName);
      };
      options.value = _options;
      show.value = true;
    });
  }
})
</script>