import { toastController, loadingController } from '@ionic/vue'
import { checkmarkOutline, closeOutline } from 'ionicons/icons'
let toastInstance = null
let loadingInstance = null
const Toast = async function (options) {
    options = options || {}
    if (typeof options === 'string') {
        options = {
            message: options
        }
    }
    options.type = options.type || 'info'
    if (toastInstance) {
        toastInstance.dismiss()
    }
    if (loadingInstance) {
        loadingInstance.dismiss()
    }
    let toastOps = {
        message: options.message,
        duration: 2000,
        translucent: false,
        position: 'top'
    }
    switch (options.type) {
        case 'info':
            toastOps.cssClass = 'info-toast'
            break
        case 'success':
            toastOps.cssClass = 'success-toast'
            toastOps.icon = checkmarkOutline
            break
        case 'error':
            toastOps.cssClass = 'error-toast'
            toastOps.icon = closeOutline
            break
    }
    const toast = await toastController.create(toastOps)
    toastInstance = toast
    toast.present()
}
;['success', 'info', 'error'].forEach(type => {
    Toast[type] = async options => {
        options = options || {}
        if (typeof options === 'string') {
            options = {
                message: options
            }
        }
        options.type = type
        return await Toast(options)
    }
})
Toast.loading = async function (options) {
    if (toastInstance) {
        toastInstance.dismiss()
    }
    if (loadingInstance) {
        loadingInstance.dismiss()
    }
    options = options || {}
    if (typeof options === 'string') {
        options = {
            message: options
        }
    }
    const loading = await loadingController.create({
        message: options.message,
        duration: options.duration || 0,
        cssClass: 'custom-loading'
    })
    loadingInstance = loading
    loading.present()
}
Toast.dismiss = Toast.clear = async () => {
    if (toastInstance) {
        toastInstance.dismiss()
    }
    if (loadingInstance) {
        loadingInstance.dismiss()
    }
}
Toast.install = (app, options) => {
    app.config.globalProperties.$toast = Toast
}
export default Toast
