const CACHE_NAME = 'SW-001';
let tipe = '0';
const toCache = [
    '/',
    '/offline.html'
];
self.addEventListener('install', function(event) {
  event.waitUntil(
      caches.open(CACHE_NAME)
      .then(function(cache) {
          return cache.addAll(toCache)
      })
      .then(self.skipWaiting())
  )
})

self.addEventListener('activate', function(event) {
  event.waitUntil(
      caches.keys()
      .then((keyList) => {
          return Promise.all(keyList.map((key) => {
          if (key !== CACHE_NAME) {
              console.log('[ServiceWorker] Hapus cache lama', key)
              return caches.delete(key)
          }
          }))
      })
      .then(() => self.clients.claim())
  )
})

self.addEventListener('fetch', event => {
  event.respondWith(
      caches.match(event.request, {
          ignoreSearch: true
      }).then(response => {
          return response || fetch(event.request);
      })
  );
});
if (navigator.serviceWorker) {
  navigator.serviceWorker.register('/firebase-messaging-sw.js').then(function(registration){
  }).catch(console.log);
}
function showNotification() {
  console.log('Buka Notifikasi');
  let notificationOptions = {
    body: 'Notifikasi',
    icon: '/images/notification.png'
  }
  let notif = new Notification('OrderIn', notificationOptions);
  notif.onclick = () => {
    console.log('Notification clicked');
  }
}
if(window.Notification) {
if(Notification.permission === 'granted') {
  console.log('Notifikasi Diizinkan');
} else if(Notification.permission !== 'denied') {

Notification.requestPermission(permission => {
  if(permission === 'granted') {
      console.log('Notifikasi Diizinkan');
  }
})
}
}

messaging.getToken({ vapidKey: 'BB6iGqCDhBCKgf5oL_TsEqM-jJdCsuQoZG-ILBgvOidgZE9p0ovk30O4W3sYf6I_kXYn6Wd3ZEjXhG-oRvC-hgA' }).then((currentToken) => {
if (currentToken) {
console.log(currentToken);
updatetoken(currentToken.toString());
return currentToken;
} else {
console.log('No registration token available. Request permission to generate one.');
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
});

messaging.onMessage(payload => {
  console.log(
    'Received message ',
    payload,
  )
if(payload.data.type.toString() == '1'){
  var a = document.createElement('a');
  a.href = targetURL;
  a.target = '_blank';
}
});

