//https://github.com/mdn/serviceworker-cookbook/tree/master

self.addEventListener('install', function(event) 
{
  event.waitUntil(self.skipWaiting());
});

self.addEventListener('activate', function(event) 
{
  event.waitUntil(self.clients.claim());
});

// Register event listener for the 'push' event.
self.addEventListener('push', function(event) 
{
  //console.log('ServiceWorker: ' + event.data.text());
  
  event.waitUntil(
    // Retrieve a list of the clients of this service worker.
    self.clients.matchAll({ type: "window" }).then(function(clientList) 
    {
      if(clientList.length == 0)
      {
        //console.log('no window clients detected');

        const sendNotification = body => {
            const title = "Poi3D Server Message";
      
            return self.registration.showNotification(title, {
                body,
            });
        };
      
        if (event.data) {
            const payload = event.data.json();
            event.waitUntil(sendNotification(payload.tXt));
        }

      }
      else
      {
        for (let client of clientList) 
        {
          client.postMessage(event.data.text());
        }
      }
    })
  );
});
