import {createApp} from 'vue'

import PageLoad from './pageLoad'
import BackgroundLoad from './backgroundLoad'


/**
 * Handles loading Vue js app on page load.
 */
export default class VueLoader {
    constructor({el=null, props={}, ...appConfig}={}, loaderOptions={}) {
        this.appConfig = appConfig
        this.appConfig.el = el
        this.props = props
        this.pageLoad = new PageLoad(el, loaderOptions)

        this.pageLoad.onPreMount = event => this.onPreMount(event)
        this.pageLoad.onMount = event => this.onMount(event)

        this.backgroundLoad = new BackgroundLoad()
    }

    enable(hotReload=true) {
        hotReload && this.pageLoad.enable(document.body)
        this.mount()
    }

    mount() {
        if(this.app)
            this.unmount()

        const app = createApp(this.appConfig, this.props)
        app.config.globalProperties.window = window
        this.vm = app.mount(this.pageLoad.el)
        this.app = app
    }

    unmount() {
        if(!this.app)
            return
        try { this.app.unmount() }
        catch(_) { null }
        this.app = null
        this.vm = null
        this.pageLoad.reset()
    }

    onPreMount() { this.unmount() }
    onMount() { this.mount() }
}
