/* ATDT SysOp console service worker (1.6.1): shows the board's push
 * notifications (a caller paging, mostly) and brings the console forward
 * when one is clicked. Registered from Settings > SysOp notifications;
 * it controls nothing and caches nothing - it only listens. */

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

self.addEventListener('push', function (e) {
  var d = {};
  try { d = e.data ? e.data.json() : {}; } catch (err) { d = {}; }
  e.waitUntil(self.registration.showNotification(d.title || 'ATDT', {
    body: d.body || 'A caller wants your attention.',
    tag: d.tag || 'atdt-page',
    renotify: true,
    data: { url: d.url || 'index.php' }
  }));
});

self.addEventListener('notificationclick', function (e) {
  e.notification.close();
  var url = (e.notification.data && e.notification.data.url) || 'index.php';
  e.waitUntil(self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function (list) {
    for (var i = 0; i < list.length; i++) {
      if (list[i].url.indexOf('/admin/') !== -1 && 'focus' in list[i]) {
        return list[i].focus();
      }
    }
    return self.clients.openWindow(url);
  }));
});
