import { mount } from '@vue/test-utils'
import Dialog from './dialog.vue'
import Window from './window.vue'
import Toast from './toast.vue'
import Alert from './alert.vue'
import Confirm from './confirm.vue'
import DialogContent from './dialog-content.vue'

Dialog.use = function use(app) {
    Dialog.toast = function (options) {
        if (typeof options == 'string') {
            options = {
                content: options,
            }
        }
        // const { destroy, vNode, el }
        const { destroy } = mount(Toast, {
            app,
            props: {
                ...options,
                destroy,
            },
        })

        if (!Dialog.toast._destroys) {
            Dialog.toast._destroys = []
        }
        Dialog.toast._destroys.push(destroy)

        return {
            hide: function () {
                let destroy = null
                while ((destroy = Dialog.toast._destroys.shift()) && destroy) {
                    destroy()
                }
            }.bind(this),
        }
    }
    Dialog.toast.hide = function () {
        if (Dialog.toast._destroys && Dialog.toast._destroys.length) {
            const destroy = Dialog.toast._destroys.pop()
            destroy && destroy()
        }
    }
    Dialog.alert = function (options) {
        if (typeof options == 'string') {
            options = {
                content: options,
            }
        }

        const { destroy } = mount(Alert, {
            app,
            props: { ...options, destroy: () => destroy() },
        })

        this.alert.hide = function () {
            destroy()
        }

        return this.alert
    }

    Dialog.confirm = function (options) {
        if (typeof options == 'string') {
            options = {
                content: options,
            }
        }

        let promise
        if (!options.func) {
            promise = new Promise(resolve => {
                options.func = result => resolve(result === 'ok')
            })
        }

        const { destroy } = mount(Confirm, {
            app,
            props: { ...options, destroy: () => destroy() },
        })

        this.confirm.hide = function () {
            destroy()
        }

        return promise || this.confirm
    }
}

export { Window, Toast, Alert, Confirm, DialogContent }

export default Dialog
