const cacheVersion = "0.56"
const cacheName = "speedtech-brainminder"
const cacheFiles = [
    "/static/datastar/datastar.js",
    "/static/easymde/easymde.min.css",
    '/static/css/slimselect.css',
    '/static/css/main.css',
    '/static/img/brainminder.svg',
    '/static/img/brainminder-icon.svg',
    "/static/easymde/easymde.min.js",
    "/static/js/Sortable.min.js",
    "/static/js/htmx/htmx.min.js",
    "/static/js/handlebars.js",
    "/static/js/templates.js",
    "/static/js/slimselect.min.js",
    '/static/js/main.js',
]

self.addEventListener('install', function(e) {
    e.waitUntil(
        // Open the cache
        caches.open(cacheName).then(function(cache) {
            // Add all the default files to the cache
            console.log('[ServiceWorker] Caching cacheFiles');
            return cache.addAll(cacheFiles);
        })
    );
});

self.addEventListener('activate', function(e) {
    e.waitUntil(
        // Get all the cache keys (cacheName)
        caches.keys().then(function(cacheNames) {
            return Promise.all(cacheNames.map(function(thisCacheName) {
                // If a cached item is saved under a previous cacheName
                if (thisCacheName !== cacheName) {
                    // Delete that cached file
                    console.log('[ServiceWorker] Removing Cached Files from Cache - ', thisCacheName);
                    return caches.delete(thisCacheName);
                }
            }));
        })
    );
});

self.addEventListener('fetch', (event) => {
    // Respond to the document with what is returned from 
    event.respondWith(
        // 1. Check the cache if a file matching that request is available
        caches.match(event.request).then((response) => {
            // 2. If it is, respond to the document with the file from the cache
            if (response) return response
            // 3. If it isn’t, fetch the file from the network and respond to the document with the fetched file
            return fetch(event.request)
        })
    );
});