// eslint-disable-next-line no-unused-vars
window.addEventListener('DOMContentLoaded', async event => {
    checkRegistration()
})

// Check a service worker registration status
async function checkRegistration() {
    if ('serviceWorker' in navigator) {
        const registration = await navigator.serviceWorker.getRegistration()
        if (registration) {
            console.log('Service worker was registered on page load')
        } else {
            console.log('No service worker is currently registered')
            register()
        }
    } else {
        console.log('Service workers API not available')
    }
}

// Registers a service worker
async function register() {
    if ('serviceWorker' in navigator) {
        try {
            // Change the service worker URL to see what happens when the SW doesn't exist
            const registration = await navigator.serviceWorker.register('sw.js')
            if (registration.waiting) {
                invokeServiceWorkerUpdateFlow(registration)
            }

            registration.addEventListener('updatefound', () => {
                // console.log('updatefound')
                if (registration.installing) {
                    // console.log('above statechange')
                    // wait until the new Service worker is actually installed (ready to take over)
                    registration.installing.addEventListener('statechange', () => {
                        // console.log('under statechange')
                        // console.log(registration.waiting)
                        if (registration.waiting) {
                            // if there's an existing controller (previous Service Worker), show the prompt
                            if (navigator.serviceWorker.controller) {
                                invokeServiceWorkerUpdateFlow(registration)
                            } else {
                                // otherwise it's the first install, nothing to do
                                // console.log('Service Worker initialized for the first time')
                            }
                        }
                    })
                }
            })

            let refreshing = false
            // detect controller change and refresh the page
            navigator.serviceWorker.addEventListener('controllerchange', () => {
                if (!refreshing) {
                    window.location.reload()
                    refreshing = true
                }
            })
            // console.log(registration)
            // console.log('Service worker registered')

        } catch (error) {
            console.log('Error while registering: ' + error.message)
        }
    } else {
        console.log('Service workers API not available')
    }
}

function invokeServiceWorkerUpdateFlow(registration) {
    const confirm = window.confirm('New version of the app is available. Refresh now?')
    if (confirm === true) {
        if (registration.waiting) {
            // let waiting Service Worker know it should became active
            registration.waiting.postMessage('SKIP_WAITING')
        }
    }
}

// Unregister a currently registered service worker
// eslint-disable-next-line no-unused-vars
async function unregister() {
    if ('serviceWorker' in navigator) {
        try {
            const registration = await navigator.serviceWorker.getRegistration()
            if (registration) {
                const result = await registration.unregister()
                console.log(result ? 'Service worker unregistered' : 'Service worker couldn`t be unregistered')
            } else {
                console.log('There is no service worker to unregister')
            }

        } catch (error) {
            console.log('Error while un-registering: ' + error.message)
        }
    } else {
        console.log('Service workers API not available')
    }
}
