"use strict";

const CACHE_NAME = "offline-cache-v1";
const OFFLINE_URL = '/offline.html';

const filesToCache = [
    OFFLINE_URL
];

self.addEventListener("install", (event) => {
    event.waitUntil(
        caches.open(CACHE_NAME)
            .then((cache) => cache.addAll(filesToCache))
    );
});

self.addEventListener("fetch", (event) => {
    if (event.request.mode === 'navigate') {
        event.respondWith(
            fetch(event.request)
                .catch(() => {
                    return caches.match(OFFLINE_URL);
                })
        );
    } else {
        event.respondWith(
            caches.match(event.request)
                .then((response) => {
                    return response || fetch(event.request);
                })
        );
    }
});

self.addEventListener('activate', (event) => {
    event.waitUntil(
        caches.keys().then((cacheNames) => {
            return Promise.all(
                cacheNames.map((cacheName) => {
                    if (cacheName !== CACHE_NAME) {
                        return caches.delete(cacheName);
                    }
                })
            );
        })
    );
});

// const CACHE_NAME = 'pds-app-cache-v1';
// const OFFLINE_URL = '/offline.html';

// const urlsToCache = [
//   '/',
//   '/admin',
//    OFFLINE_URL,
//   '/icons/icon-192x192.png',
//   '/icons/icon-512x512.png'
// ];

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

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

// self.addEventListener('fetch', event => {
//   if (event.request.mode === 'navigate') {
//     event.respondWith(
//       fetch(event.request).catch(() =>
//         caches.match(OFFLINE_URL)
//       )
//     );
//   } else {
//     event.respondWith(
//       caches.match(event.request).then(response =>
//         response || fetch(event.request)
//       )
//     );
//   }
// });
