var publicKey = 'BNan2ZkZRV6skCmS9rAJx5jb0eZgjo1-hmil3ZkhJs20yDOpBpEFaV9p1mag6KfBItZdzCT9-8pt15GSIIGV5DE'
if (location.hostname === '127.0.0.1' || location.hostname === 'localhost') {
  publicKey = 'BAEJLGwWlflC8M1aN2Xj2GEwNp5_2Lv_-yjm29XVT93nbgdZkSH4pqDYKx60wjt0oyUg1Fw_LlEfs3i3-Lgi2yw'
}

let isSubscribed = false
let swRegistration = null

// 转换
function urlBase64ToUint8Array (base64String) {
  const padding = '='.repeat((4 - base64String.length % 4) % 4)
  const base64 = (base64String + padding)
    .replace(/-/g, '+')
    .replace(/_/g, '/')

  const rawData = window.atob(base64)
  const outputArray = new Uint8Array(rawData.length)

  for (let i = 0; i < rawData.length; ++i) {
    outputArray[i] = rawData.charCodeAt(i)
  }
  return outputArray
}

let pushMsgPlugin = {}
pushMsgPlugin.install = function (Vue, options) {
  Vue.prototype.$submitData = function (subscription) {
    if (subscription) {
      const key = subscription.getKey('p256dh')
      const token = subscription.getKey('auth')
      const contentEncoding = (PushManager.supportedContentEncodings || ['aesgcm'])[0]
      let publicKey = key ? btoa(String.fromCharCode.apply(null, new Uint8Array(key))) : null
      let authToken = token ? btoa(String.fromCharCode.apply(null, new Uint8Array(token))) : null
      let data = JSON.stringify({
        endpoint: subscription.endpoint,
        publicKey: publicKey,
        authToken: authToken,
        contentEncoding
      })
      let player = this.$store.state.account
      this.$axios.post('messaging/setPlayerInfo', {
        player: player.name,
        info: data,
        token: sessionStorage.getItem('token'),
        account: sessionStorage.getItem('account')
      }).then(function (data) {
        console.log(data)
      }).catch(function (error) {
        console.log(error)
      })
    }
  }
  Vue.prototype.$getSubscription = function () {
    let that = this
    const subscribeOptions = {
      userVisibleOnly: true,
      applicationServerKey: urlBase64ToUint8Array(publicKey)
    }
    // 接口的subscribe()方法PushManager订阅推送服务。
    // 它返回一个Promise解析为PushSubscription包含推送订阅细节的对象。如果当前服务工作者没有现有订阅，则会创建新的推送订阅。
    if (!isSubscribed) {
      // TODO: Unsubscribe user
      swRegistration.pushManager.subscribe(subscribeOptions).then(function (subscription) {
        // console.log(JSON.stringify(subscription));
        that.$submitData(subscription)
      }).catch(function (error) {
        console.log(error)
      })
    }
  }

  Vue.prototype.$pushMsg = async function () {
    let that = this
    let swPath = 'dist/static/sw.js'
    if (location.hostname === '127.0.0.1' || location.hostname === 'localhost') {
      swPath = 'static/sw.js'
    }

    if ('serviceWorker' in navigator && 'PushManager' in window) {
      navigator.serviceWorker.register(swPath).then(function (registration) {
        console.log('成功注册 Service worker')
        swRegistration = registration
        // 检索现有的推送订阅
        swRegistration.pushManager.getSubscription()
          .then(function (subscription) {
            isSubscribed = !(subscription === null)
            that.$submitData(subscription)
          })
      })
        .catch(function (error) {
          console.error(error)
        })
    } else {
      console.warn('你的浏览器不支持通知推送服务')
      // alert('你的浏览器不支持通知推送服务');
    }
  }
}

export default pushMsgPlugin
