<file_sep>// variables
var swRegistration;
var isSubscribed;
const publicServerKey = '<KEY>';
const subscribeButton = document.querySelector('#btnSubscribe');

// register service worker
if ('serviceWorker' in navigator && 'PushManager' in window) {
  console.log('Push notification supported!');

  navigator.serviceWorker.register('sw.js')
  .then(function(swReg){
    console.log('Service worker registered successfully!');
    swRegistration = swReg;
    initUI();
  }).catch(function(err) {
    console.error('Service Worker not registered ' + err);
  });
} else {
  console.error('Push notification NOT supported!')
}

// initialize UI and get subscription details
function initUI() {
  subscribeButton.addEventListener('click', function() {
    subscribeButton.disabled = true;
    if (isSubscribed) {
      unsubscribeUser();
    } else {
      subscribeUser();
    }
  });

  // tries to get details of active subscription
  swRegistration.pushManager.getSubscription()
  .then(function(subscription) {
    isSubscribed = !(subscription === null);

    if (isSubscribed) {
      console.log('User\'s subscription is active!');
      // write to output subscription details
      console.log(JSON.stringify(subscription));
    } else {
      console.log('User is not subscribed!');
    }

    updateSubscriptionButton();
  });
}

// refreshes the state of the "Subscribe / unsubscribe" button
function updateSubscriptionButton() {
  if (isSubscribed) {
    subscribeButton.textContent = 'Unsubscribe';
  } else {
    subscribeButton.textContent = 'Subscribe';
  }

  subscribeButton.disabled = false;
}

// subscribe user
function subscribeUser() {
  var publicKey = urlB64ToUint8Array(publicServerKey);

  swRegistration.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: publicKey
  }).then(function(subscription){
    isSubscribed = true;
    console.log('User successfully subscribed');
    console.log(JSON.stringify(subscription));
    updateSubscriptionButton();
    registerSubscriptionOnServer(subscription);
    
  }).catch(function(err) {
    console.log('Unable to subscribe user ', err);
  });
}

// unsubscribe user
function unsubscribeUser() {
  var subscriptionObject;
  swRegistration.pushManager.getSubscription()
  .then(function(subscription) {
    if (subscription) {
      subscriptionObject = subscription;
      return subscription.unsubscribe();
    }
  }).catch(function(err) {
    console.error('Cannot unsubscribe user ', err);
  }).then(function() {
    // unsegister user on server
    console.log("User successfully unsubscribed");
    isSubscribed = false;
    unregisterSubscriptionOnServer(subscriptionObject);
    updateSubscriptionButton();
  });
}

function registerSubscriptionOnServer(subscription) {
  fetch('/registerSubscription', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            subscription: subscription,          
            })            
        });
}

function unregisterSubscriptionOnServer(subscription) {
  fetch('/unregisterSubscription', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            subscription: subscription,          
            })            
        });
}

// converts VAPID public key to UInt 8 bit array required to subscribe user
function urlB64ToUint8Array(base64String) {
  const padding = '='.repeat((4 - base64String.length % 4) % 4);
  const base64 = (base64String + padding)
    .replace(/\-/g, '+')
    .replace(/_/g, '/');

  const rawData = window.atob(base64);
  const outputArray = new Uint8Array(rawData.length);

  for (let i = 0; i < rawData.length; ++i) {
    outputArray[i] = rawData.charCodeAt(i);
  }
  return outputArray;
}<file_sep>// Register event listener for the 'push' event.
self.addEventListener('push', function(event) {
    console.log('Received a push message', event);
  
  var  data = event.data.json();
  console.log(JSON.stringify(data));

  // Keep the service worker alive until the notification is created.
  event.waitUntil(
    
    self.registration.showNotification(data.title, {
      body: data.body,
      icon: data.icon,
      vibrate: data.vibrate,
      actions: data.actions,
      requireInteraction: data.requireInteraction
    })
  );
});

self.addEventListener('notificationclick', function(event) {
  event.notification.close();
if (event.action === 'yes') {
    console.log('Clicked yes');
  } else if (event.action === 'no') {
    console.log('Clicked no');
  } else {
    console.log('Clicked nothing');
  }
});

self.addEventListener('notificationclose', function(event) {
  console.log('Closed');
});<file_sep>var reqInt = false;         // require interaction

function sendBasicPushMessage() {
// TO DO simple push done
// push with icon - done
// push with vibration
// push with actions
// pust to specified users

    fetch('/api/send-push', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            data: JSON.stringify({title: 'Simple push notification',
                    body: 'This is what a basic push notification looks like.',
                    requireInteraction: reqInt
            })            
        })
    }).then((response) => {
        console.log(response);
    });
}

function sendPushMessageWithIcon() {
    fetch('/api/send-push', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            data: JSON.stringify({title: 'Push notification with icon',
                    body: 'This is what a push notification with icon looks like.',
                    icon: './web_app/images/notification.png',
                    requireInteraction: reqInt
            })            
        })
    }).then((response) => {
        console.log(response);
    });
}

function sendPushMessageWithVibrating() {
    fetch('/api/send-push', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            data: JSON.stringify({title: 'Push notification with vibrating',
                    body: 'This is what a push notification with vibrating.',
                    icon: './web_app/images/vibrating.png',
                    vibrate: [200, 100, 200, 100, 200, 100, 200],
                    requireInteraction: reqInt
            })            
        })
    }).then((response) => {
        console.log(response);
    });
}

function sendPushMessageWithAction() {
    fetch('/api/send-push', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            data: JSON.stringify({title: 'Push notification with Action',
                    body: 'This is what a push notification with Action',
                    icon: './web_app/images/like_demo.png',
                    vibrate: [200, 100, 300, 100, 200, 100, 400],
                    actions: [{ "action": "yes", "title": "Yes!!!", "icon": "./web_app/images/yes.png" },
                            { "action": "no", "title": "No!!!", "icon": "./web_app/images/no.png" }],
                    requireInteraction: reqInt     
            })            
        })
    }).then((response) => {
        console.log(response);
    });
}

function sendPushMessageWithCustomBadge() {
    fetch('/api/send-push', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            data: JSON.stringify({title: 'Push notification with Custom Badge',
                    body: 'This is what a push notification with custom badge',
                    icon: './web_app/images/coffee.png',
                    badge: './web_app/images/coffee-beans.png',
                    vibrate: [200, 100, 300, 100, 200, 100, 400],                    
                    requireInteraction: reqInt     
            })            
        })
    }).then((response) => {
        console.log(response);
    });
}

function initUI() {
    const basicPushNotificationBtn = document.querySelector('#btnSimplePush');
    basicPushNotificationBtn.addEventListener('click', () => {
        sendBasicPushMessage();    
    });

    const pushNotificationWithIconBtn = document.querySelector('#btnPushWithIcon');
    pushNotificationWithIconBtn.addEventListener('click', () => {
        sendPushMessageWithIcon();
    });

    const pushNotificationWithVibratingBtn = document.querySelector('#btnPushWithVibrating');
    pushNotificationWithVibratingBtn.addEventListener('click', () => {
        sendPushMessageWithVibrating();
    });

    const pushNotificationWithCustomBadge = document.querySelector('#btnPushWithCustomBadge');
    pushNotificationWithCustomBadge.addEventListener('click', () => {
        sendPushMessageWithCustomBadge();
    });

    const pushNotificationWithActionBtn = document.querySelector('#btnPushNotificationWithAction');
    pushNotificationWithActionBtn.addEventListener('click', () => {
        sendPushMessageWithAction();
    });

    const requireInteractionsCheckbox = document.querySelector('#chbRequireInteraction');
    requireInteractionsCheckbox.addEventListener('click', () => {
        reqInt = requireInteractionsCheckbox.checked;
    });
}

window.addEventListener('load', () => {
    initUI();
});