import { createVNode, render } from 'vue'
import LoadingCom from '../components/loading/Loading.vue'

const name = 'loading'
const key = `__${name}`

const mountHandler = (el, binding, vnode) => {
    el[key] = {
        mountEl: document.createElement('div'),
    }
}

const updateHandler = (el, binding, vnode) => {
    const config = el[key]

    if (binding.value && !config.loadVnode) {
        config.loadVnode = createVNode(LoadingCom, { el, size: 10 })
        render(config.loadVnode, config.mountEl)
    } else if (!binding.value && config.loadVnode) {
        config.loadVnode = null
        render(null, config.mountEl)
    }
}
const unmountHandler = el => {
    delete el[key]
}

export default {
    name,
    hook: {
        beforeMount: mountHandler,
        beforeUpdate: updateHandler,
        beforeUnmount: unmountHandler,
    },
}
