const VERSION = '1.19';
const CACHE_NAME = `gottesdienste-v${VERSION}`;
const assets = [
  '/', 
  `/static/app.css?v=${VERSION}`,
  `/static/app.js?v=${VERSION}`,
  `/static/gallery.css?v=${VERSION}`,
  `/static/gallery.js?v=${VERSION}`,
  `/static/audioplayer.css?v=${VERSION}`,
  `/static/audioplayer.js?v=${VERSION}`,
  '/icon/logo-192x192.png',
  '/icon/logo-300x300.png',
  '/icon/logo-512x512.png',
  '/custom_logo/logoB.png',
  '/custom_logo/logoW.png'
];

self.addEventListener('install', evt => {
  self.skipWaiting();
  evt.waitUntil(
    caches.open(CACHE_NAME)
      .then(cache => cache.addAll(assets))
  );
});

self.addEventListener('activate', evt => {
  self.clients.claim();
  evt.waitUntil(
    caches.keys().then(keys =>
      Promise.all(
        keys
          .filter(k => k !== CACHE_NAME)
          .map(k => caches.delete(k))
      )
    )
    .then(() => {
      // Reload to use new files
      return self.clients.matchAll({ type: 'window' })
        .then(clients =>
          clients.forEach(client => client.navigate(client.url))
        );
    })
  );
});

self.addEventListener('fetch', evt => {
  if (evt.request.mode === 'navigate') {
    evt.respondWith(
      fetch(evt.request).catch(() => caches.match('/app.html'))
    );
    return;
  }
  evt.respondWith(
    caches.match(evt.request).then(cached => cached || fetch(evt.request))
  );
});
