//--------------------------------------------------------------------------
// You can find dozens of practical, detailed, and working examples of 
// service worker usage on https://github.com/mozilla/serviceworker-cookbook
//--------------------------------------------------------------------------

// Cache version
var CACHE_VERSION = '5.8'

// Cache name
var CACHE_NAME = 'cyradrive'+CACHE_VERSION;

// Files
var REQUIRED_FILES = [
  '/',
  'index.html',
  '/assets/css/style.css',
  '/assets/js/base.js',
  '/manifest.json',
  '/assets/img/icon/icon-512x512.png',
  '/assets/img/icon/icon-192x192.png'
];


// Install event - Precache all required files
self.addEventListener('install', function (event) {
  console.log('[ServiceWorker] Install');
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function (cache) {
        console.log('[ServiceWorker] Caching required files');
        return cache.addAll(REQUIRED_FILES);
      })
      .then(() => self.skipWaiting())
      .catch(function (error) {
        console.error('[ServiceWorker] Caching failed:', error);
      })
  );
});

// Activate event - Clean up old caches
self.addEventListener('activate', function (event) {
  console.log('[ServiceWorker] Activate');
  event.waitUntil(
    caches.keys().then(function (cacheNames) {
      return Promise.all(
        cacheNames.map(function (cacheName) {
          if (cacheName !== CACHE_NAME) {
            console.log('[ServiceWorker] Deleting old cache:', cacheName);
            return caches.delete(cacheName);
          }
        })
      );
    }).then(() => self.clients.claim())
  );
});


self.addEventListener('fetch', function (event) {
  event.respondWith(
    caches.match(event.request)
      .then(function (response) {
        // Cache hit - return the response from the cached version
        if (response) {
          return response;
        }
        // Not in cache - return the result from the live server
        // `fetch` is essentially a "fallback"
        return fetch(event.request);
      }
      )
  );
});

self.addEventListener('activate', function (event) {
  // Calling claim() to force a "controllerchange" event on navigator.serviceWorker
  event.waitUntil(self.clients.claim());
});