var periodicSyncNewMsgReminderText;

// Notification click event listener
self.addEventListener("notificationclick", (e) => {
  e.notification.close();
  e.waitUntil(
    clients.matchAll({ type: "window" }).then((clientsArr) => {
      // If a Window tab matching the targeted URL already exists, focus that;
      const hadWindowToFocus = clientsArr.some((windowClient) =>
        windowClient.url === e.notification.data.url
          ? (windowClient.focus(), true)
          : false,
      );

      // Otherwise, open a new tab to the applicable URL and focus it.
      if (!hadWindowToFocus)
        clients
          .openWindow(e.notification.data.url)
          .then((windowClient) => (windowClient ? windowClient.focus() : null));
    }),
  );
});

self.addEventListener("message", (event) => {
  periodicSyncNewMsgReminderText = event.data;
});

async function checkNewMessages() {
  const cachedCredentials = await caches.open('cachedCredentials');
  // Todo...
}

// Install PWA in mobile or web to test if periodicSync notification works
// see browser compatibility: https://developer.mozilla.org/en-US/docs/Web/API/Web_Periodic_Background_Synchronization_API#browser_compatibility
self.addEventListener('periodicsync', (event) => {
  if (event.tag === 'check-new-messages') {
    let notificationTitle = periodicSyncNewMsgReminderText || "You may have new messages";
    self.registration.showNotification(notificationTitle);

    event.waitUntil(checkNewMessages());
  }
});
