const CACHE_NAME = 'gottesdienste-app-v1.3';
const ASSETS = [
  '/',
  '/static/app.css',
  '/static/app.js',
  '/static/gallery.css',
  '/static/gallery.js',
  '/static/audioplayer.css',
  '/static/audioplayer.js',
  '/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))
      )
    )
  );
});

const RICH_MEDIA_TYPES = ['style', 'script', 'font'];

async function networkFirst(request) {
  const cache = await caches.open(CACHE_NAME);
  try {
    const fresh = await fetch(request);
    cache.put(request, fresh.clone());
    return fresh;
  } catch (err) {
    const cached = await cache.match(request);
    if (cached) return cached;
    throw err;
  }
}

async function cacheFirst(request) {
  const cache = await caches.open(CACHE_NAME);
  const cached = await cache.match(request);
  if (cached) return cached;
  const fresh = await fetch(request);
  cache.put(request, fresh.clone());
  return fresh;
}

self.addEventListener('fetch', evt => {
  const { request } = evt;
  if (request.method !== 'GET') return;

  if (request.mode === 'navigate') {
    evt.respondWith(
      fetch(request).catch(() => caches.match('/'))
    );
    return;
  }

  if (RICH_MEDIA_TYPES.includes(request.destination)) {
    evt.respondWith(networkFirst(request));
    return;
  }

  evt.respondWith(cacheFirst(request));
});
