const PYRK_CACHE = 'pyrk-app-shell-v1';
const CORE_ASSETS = [
  '/steps/public/offline.html',
  '/steps/public/assets/css/pwa_app_shell.css'
];

self.addEventListener('install', event => {
  event.waitUntil(caches.open(PYRK_CACHE).then(cache => cache.addAll(CORE_ASSETS)).then(() => self.skipWaiting()));
});

self.addEventListener('activate', event => {
  event.waitUntil(
    caches.keys().then(keys => Promise.all(keys.filter(key => key !== PYRK_CACHE).map(key => caches.delete(key))))
      .then(() => self.clients.claim())
  );
});

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

  if (request.mode === 'navigate') {
    event.respondWith(fetch(request).catch(() => caches.match('/steps/public/offline.html')));
    return;
  }

  event.respondWith(
    caches.match(request).then(cached => cached || fetch(request).catch(() => cached))
  );
});
