/* tslint:disable:no-console */

import { register } from 'register-service-worker'
import notif from './utils/notif'

if (process.env.NODE_ENV === 'production') {
  const enableNotif: boolean = false
  let newWorker: any | undefined

  const reloadLink = document.getElementById('reload-notify-worker')
  if (reloadLink) {
    reloadLink.addEventListener('click', () => {
      if (newWorker) {
        newWorker.postMessage({ action: 'skipWaiting' })
      }
    })
  }
  const showUpdateBar = () => {
    const notify = document.getElementById('notify-worker')
    if (notify) {
      notify.classList.add('show')
    }
  }
  register(`${process.env.BASE_URL}service-worker.js`, {
    registrationOptions: {},
    ready() {
      notif.success('Application mise à jour !')
      console.log(
        'App is being served from cache by a service worker.\n' +
          'For more details, visit https://goo.gl/AFskqB'
      )
    },
    cached() {
      console.log('Content has been cached for offline use.')
    },
    updatefound(reg) {
      if (enableNotif) {
        console.log('New content found;')
        newWorker = reg.installing

        newWorker.addEventListener('statechange', () => {
          // Has network.state changed?
          switch (newWorker.state) {
            case 'installed':
              if (navigator.serviceWorker.controller) {
                // new update available
                showUpdateBar()
              }
              // No update available
              break
          }
        })
      }
    },
    updated() {
      console.log('New content is available; please refresh.')
    },
    offline() {
      console.log(
        'No internet connection found. App is running in offline mode.'
      )
    },
    error(error) {
      console.error('Error during service worker registration:', error)
    }
  })
  let refreshing: any | undefined
  navigator.serviceWorker.addEventListener('controllerchange', () => {
    if (refreshing) {
      return
    }
    window.location.reload()
    refreshing = true
  })
}
