if (firebaseConfig != null) {

  importScripts('/silverpeas/spmobile/firebasejs/7.12.0/firebase-app.js');
  importScripts('/silverpeas/spmobile/firebasejs/7.12.0/firebase-messaging.js');

  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);

  const messaging = firebase.messaging();

  messaging.setBackgroundMessageHandler(function(payload) {
    console.log('[firebase-messaging-sw.js] Received background message ', payload);
    const notificationTitle = payload.data["subject"];
    const notificationOptions = {
      body : payload.data["body"], icon : '/silverpeas/util/icons/desktop-user-notification.png',
      data : payload.data
    };

    return self.registration.showNotification(notificationTitle, notificationOptions);
  });

  // Service worker notification management
  self.addEventListener("notificationclick", function(event) {
     const pushData = event.notification.data;
     event.notification.close();
     if (!pushData["permalink"].endsWith("/null")) {
      fetch('/silverpeas/services/mobile/notification/readed/' + pushData["notificationId"], {
        method: 'PUT'
      });

      event.waitUntil(clients.matchAll({type: "window", includeUncontrolled: true}).then(function (clientList) {
          if (pushData["permalink"]) {
              let client = null;
              for (let i = 0; i < clientList.length; i++) {
                  let item = clientList[i];
                  if (item.url) {
                      client = item;
                      break;
                  }
              }
              if (client && 'navigate' in client) {
                  client.focus();
                  event.notification.close();
                  return client.navigate(pushData["permalink"]);
              }
              else {
                  event.notification.close();
                  // if client doesn't have navigate function, try to open a new browser window
                  return clients.openWindow(pushData["permalink"]);
              }
          }
      }));

     }
  });

}

const CACHE_NAME = 'spmobileOffline';
var cache;

self.addEventListener('install', (event) => {
  console.log('Install service worker');
  event.waitUntil((async () => {
    cache = await caches.open(CACHE_NAME);
    await cache.addAll(OFFLINE_URLS);
    return self.skipWaiting();
  })());
});

self.addEventListener('activate', function(event) {
  event.waitUntil((async () => {
    cache = await caches.open(CACHE_NAME);
    return self.clients.claim();
  })());
});


self.addEventListener('fetch', function(event) {
    if (event.request.method == 'GET' && event.request.url.startsWith('http') && event.request.url.indexOf("9876") === -1) {
      event.respondWith(
        fetch(event.request).then(function(response){
                      try {
                        if (event.request.url.includes('.cache.js')) {

                          console.log('clean old nocache.js');
                          cache.keys().then(function(cachedRequests) {
                            cachedRequests.forEach(function(cachedRequest) {
                              if (cachedRequest.url.includes('.cache.js')) {
                                console.log('old cache.js found !');
                                cache.delete(cachedRequest);
                              }
                            });
                          });

                        }
                        cache.put(event.request.clone(), response.clone());

                      } catch(error) {
                        if (error.name === 'QuotaExceededError') {
                          console.log('cleaning cache');
                          cache.keys().then(function(cachedRequests) {
                            cachedRequests.forEach(function(cachedRequest) {
                              if (cachedRequest.url.includes('/services/')) {
                                cache.delete(cachedRequest);
                              }
                            });
                          });
                        }
                      }


		          //console.log('Réponse du réseau :', response);
              return response;

          }).catch(function() {
		        return caches.match(event.request);
          })
        );
      }
  });


