///
/// Thomas Berrod
/// A generic service worker
/// inspired by https://github.com/gauntface/web-push-book
///

; (function () {
  "use strict";

  self.importScripts('/static/js/analytics-helper.js');

  function focusWindow(event) {
    const url = event.notification.data["link"]; //TODO : there are 2 web server now...
    const urlToOpen = new URL(url, self.location.origin).href;

    const promiseChain = clients.matchAll({
      type: 'window',
      includeUncontrolled: true
    })
      .then((windowClients) => {
        let matchingClient = null;

        for (let i = 0; i < windowClients.length; i++) {
          const windowClient = windowClients[i];
          if (windowClient.url === urlToOpen) {
            matchingClient = windowClient;
            break;
          }
        }

        if (matchingClient) {
          return matchingClient.focus();
        } else {
          return clients.openWindow(urlToOpen);
        }
      });
    event.waitUntil(promiseChain);
  }

  function isClientFocused() {
    return clients.matchAll({
      type: 'window',
      includeUncontrolled: true
    })
      .then((windowClients) => {
        let clientIsFocused = false;

        for (let i = 0; i < windowClients.length; i++) {
          const windowClient = windowClients[i];
          if (windowClient.focused) {
            clientIsFocused = true;
            break;
          }
        }

        return clientIsFocused;
      });
  }

  function demoMustShowNotificationCheck(event) {
    const promiseChain = isClientFocused()
      .then((clientIsFocused) => {
        if (clientIsFocused) {
     
          //could alert 
          demoSendMessageToPage(event);
          return;
        }

        // Client isn't focused, we need to show a notification.
        return self.registration.showNotification(
          event.data.json().notification.title,
          event.data.json().notification);
      });

    event.waitUntil(promiseChain);
  }

  function demoSendMessageToPage(event) {

    const promiseChain = isClientFocused()
      .then((clientIsFocused) => {
        if (clientIsFocused) {
          clients.matchAll({
            type: 'window',
            includeUncontrolled: true
          }).then((windowClients) => {
            let clientIsFocused = false;

            for (let i = 0; i < windowClients.length; i++) {
              const windowClient = windowClients[i];
              if (windowClient.focused) {
                console.info('Posting message to page');
                windowClient.postMessage(event.data.json().notification);
              }
            }
          });

        } else {
          return self.registration.showNotification('No focused windows', {
            body: 'Had to show a notification instead of messaging each page.'
          });
        }
      });

    event.waitUntil(promiseChain);
  }

  self.addEventListener('push', function (event) {

    demoMustShowNotificationCheck(event);

  });

  self.addEventListener('notificationclick', function (event) {
    event.waitUntil(
      sendAnalyticsEvent('click', 'Push', event.notification.title)
    );

    event.notification.close();
    switch (event.notification.tag) {
      case 'open-window':
        focusWindow(event);
        break;
      default:
        // 
        break;
    }
  });

  const notificationCloseAnalytics = () => {
    return Promise.resolve();
  };

  self.addEventListener('notificationclose', function (event) {
    const dismissedNotification = event.notification;
    event.waitUntil(
      sendAnalyticsEvent('close', 'Push', event.notification.title)
    );
    const promiseChain = notificationCloseAnalytics();
    event.waitUntil(promiseChain);
  });

})()