import { reactive } from 'vue'

export const dialogState = reactive({
  visible: false,
  type: 'alert', // 'alert', 'confirm', 'prompt'
  message: '',
  defaultValue: '',
  okText: '',
  cancelText: '',
  resolve: null
})

export function showAlert(msg) {
  return new Promise(resolve => {
    dialogState.visible = true
    dialogState.type = 'alert'
    dialogState.message = msg
    dialogState.okText = ''
    dialogState.cancelText = ''
    dialogState.resolve = resolve
  })
}

export function showConfirm(msg, opts = {}) {
  return new Promise(resolve => {
    dialogState.visible = true
    dialogState.type = 'confirm'
    dialogState.message = msg
    dialogState.okText = opts.okText || ''
    dialogState.cancelText = opts.cancelText || ''
    dialogState.resolve = resolve
  })
}

export function showPrompt(msg, defaultVal = '') {
  return new Promise(resolve => {
    dialogState.visible = true
    dialogState.type = 'prompt'
    dialogState.message = msg
    dialogState.defaultValue = defaultVal
    dialogState.resolve = resolve
  })
}

export function closeDialog(result) {
  dialogState.visible = false
  if (dialogState.resolve) dialogState.resolve(result)
  dialogState.resolve = null
}
