// Setup the animation loop.
import TWEEN from '@tweenjs/tween.js'

function animate (time) {
  requestAnimationFrame(animate)
  TWEEN.update(time)
}
requestAnimationFrame(animate)

if ('serviceWorker' in navigator) {
  let scriptUrl = '/sw.js'

  navigator.serviceWorker.register(scriptUrl).then(function (reg) {
    if (reg.installing) {
      console.log('Service worker installing')
    } else if (reg.waiting) {
      console.log('Service worker installed')
    } else if (reg.active) {
      console.log('Service worker active')
    }

    reg.addEventListener('updatefound', function () {
      if (navigator.serviceWorker.controller) {
        var installingWorker = reg.installing
        installingWorker.onstatechange = function () {
          console.log('installingWorker.state:' + installingWorker.state)
          switch (installingWorker.state) {
            case 'installed':
              // MessageBox.confirm('新的内容已更新完毕，立即刷新页面？', '提示', {
              //   confirmButtonText: '确定',
              //   cancelButtonText: '取消'
              // }).then(() => {
              //   location.reload()
              // }).catch(() => {})

              break
            case 'redundant':
              break
            default:
          }
        }
      }
    })

    if (navigator.serviceWorker) {
      navigator.serviceWorker.addEventListener('statechange', function (e) {
        console.log('statechange: ', e.target.state)
      })
    }
  }).catch(function (error) {
    // registration failed
    console.log('Registration failed with ' + error)
  })
}

// 监听localStorage的变化，user_id变化时，要刷新
window.addEventListener('storage', (event) => {
  if (event.key === 'user_id') {
    location.reload()
  }
})

// 触发pwa的安装实践
var btnPwa = null
var deferredPrompt = null

window.addEventListener('beforeinstallprompt', function (e) {
  if (!btnPwa) {
    initPwaBtn()
  }

  deferredPrompt = e
  // 取消默认事件
  e.preventDefault()
  return false
})

function initPwaBtn () {
  btnPwa = document.getElementById('btnPwa')
  if (!btnPwa) {
    return
  }

  btnPwa.style.display = 'block'
  btnPwa.addEventListener('click', function () {
    if (deferredPrompt != null) {
      deferredPrompt.prompt()
      // 检测用户的安装行为
      deferredPrompt.userChoice.then(function (choiceResult) {
        console.log(choiceResult.outcome)

        if (choiceResult.outcome === 'dismissed') {
          console.log('用户取消安装应用')
        } else {
          console.log('用户安装了应用')
          btnPwa.style.display = 'none'
        }
      })

      deferredPrompt = null
    }
  })
}
