// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here. Other Firebase libraries
// are not available in the service worker.
importScripts('https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.10.1/firebase-messaging.js');

// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
firebase.initializeApp({
    apiKey: 'AIzaSyCDsCxRRcJ83ypHGg0-hff90Cwft-CE9ko',
    authDomain: 'marketing-confort-d3e8a.firebaseapp.com',
    projectId: 'marketing-confort-d3e8a',
    storageBucket: 'marketing-confort-d3e8a.appspot.com',
    messagingSenderId: '1018155471512',
    appId: '1:1018155471512:web:fbb37f5638b7bb48dcf6ed',
    measurementId: 'G-5NCZ0DT3YQ'
});

// Retrieve an instance of Firebase Messaging so that it can handle background messages.

  const messaging = firebase.messaging();
  let urlToOpen = 'https://menulik.com';
  messaging.setBackgroundMessageHandler(function(payload) {
    return new Promise((resolve, reject) => {
        const request = indexedDB.open('firebase-userInfo-database', 1);

        request.onsuccess = function(event) {
            const db = event.target.result;
            const transaction = db.transaction('settings', 'readonly');
            const store = transaction.objectStore('settings');
            const getRequest = store.get('loggedUserInfos');

            getRequest.onsuccess = function(event) {
                const result = event.target.result;
                if (result && result.value && (result.value.role === "ADMIN" || result.value.uuid === payload.data.waiterUuid)) {
                    const notificationTitle = payload.data.title;
                    const notificationOptions = {
                        body: payload.data.body,
                        icon: payload.data.image,
                    };
                    self.registration.showNotification(notificationTitle, notificationOptions);
                }
                resolve();
            };

            getRequest.onerror = function() {
                resolve();
            };
        };
    });
  });

  
  self.addEventListener('notificationclick', (event) => {
    event.notification.close(); 
    event.waitUntil(
      clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
        for (const element of clientList) {
          const client = element;
          if (client.url === urlToOpen && 'focus' in client) {
            return client.focus();
          }
        }
        if (clients.openWindow) {
          return clients.openWindow(urlToOpen);
        }
      })
    );
    
  });



  
  