importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-messaging-compat.js');
importScripts('swenv.js')
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('./firebase-messaging-sw.js').then(function (reg) {
    console.log('reg: ', reg.scope);
  }).catch(function (err) {
    console.log('err: ', err);
  })
}
class CustomPushEvent extends Event {
  constructor(data) {
    super('push')

    Object.assign(this, data)
    this.custom = true
  }
}

firebase.initializeApp({
  apiKey: process.env.NEXT_PUBLIC_FIREBASE_APIKEY,
  authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTHDOMAIN,
  projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECTID,
  storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGEBUCKET,
  messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGINGSENDERID,
  appId: process.env.NEXT_PUBLIC_FIREBASE_APPID,
  measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENTID,
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
self.addEventListener('push', (e) => {
  // Skip if event is our own custom event
  console.log(`🚀🚀🚀🚀🚀-> in firebase-messaging-sw.js on 41`, e);
  if (e.custom) return;

  // Kep old event data to override
  let oldData = e.data

  // Create a new event to dispatch, pull values from notification key and put it in data key,
  // and then remove notification key
  let newEvent = new CustomPushEvent({
    data: {
      json() {
        let newData = oldData.json()
        newData.data = {
          ...newData.data,
          ...newData.notification
        }
        delete newData.notification
        return newData
      },
    },
    waitUntil: e.waitUntil.bind(e),
  })

  // Stop event propagation
  e.stopImmediatePropagation()

  // Dispatch the new wrapped event
  dispatchEvent(newEvent)
})

const messaging = firebase.messaging();

messaging.onBackgroundMessage( (payload) => {
  console.log(`🚀🚀🚀🚀🚀-> in firebase-messaging-sw.js on 24`,payload)
  // Customize notification here
  const notificationTitle = payload.data.title;
  const notificationOptions = {
    body: payload.data.body,
    icon: payload.data.image,
    data: payload.data,
   ...payload.data
  };
  return self.registration.showNotification(notificationTitle,
    notificationOptions);
});

self.onnotificationclick = function (event) {
  console.log(`🚀🚀🚀🚀🚀-> in firebase-messaging-sw.js on 91`,event);
  //example
  self.clients.openWindow('/')
  event.notification.close()
}
