const CACHE_NAME_RHB = 'sefir-v3.2.2'; //self.APP_VERSION_RHB;
console.log(CACHE_NAME_RHB); // Esto imprimirá el nombre del caché con la fecha formateada
const urlsToCacheRhb = [
  'index.html',
  'open.html',
  'openvideo.html',
  'newpdf.html',
  'settings.html',
  'manifest.json',
  'adherencia.html',
  'ejechart.html',
  'imgchart.html',
  'encuestaplus.html',
  'encuesta.html',
  'encuestalite.html',
  'js/index.js',
  'js/jssetup.js'
  /*,
  '../html/open.js',
  '../html/adherencia.js',
  '../html/ejechart.js',
  '../html/imgchart.js',
  '../html/encuestaplus.js',
  '../html/encuesta.js',
  '../js/varrhb.js',
  '../js/html5-qrcode.min.js',
  '../js/jspdf.umd.min.js',
  '../js/pdf.min.js',
  '../js/pdf.worker.min.js',
  '../js/qrious.min.js'*/
];

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

self.addEventListener("activate", event => {
  event.waitUntil(
    caches.keys()
      .then(keys => Promise.all(
        keys.filter(key => key !== CACHE_NAME_RHB).map(key => caches.delete(key))
      ))
      .then(() => self.clients.claim())
      .then(() => self.clients.matchAll())
      .then(clients => clients.forEach(client =>
        client.postMessage({ version: CACHE_NAME_RHB })
      ))
  );
});

////////////////////////////////

// Intercepción de peticiones (fetch)
self.addEventListener('fetch', (event) => {
  if (event.request.method !== 'GET') return;

  // Dejar que el navegador gestione las navegaciones HTML directamente
  if (event.request.mode === 'navigate') return;
  if (event.request.destination === 'document') return;
  const reqUrl = new URL(event.request.url);
  if (reqUrl.pathname.endsWith('.html')) return;

  event.respondWith(
    caches.match(event.request).then((cachedResponse) => {
      if (cachedResponse) return cachedResponse;

      return fetch(event.request).then((networkResponse) => {
        if (!networkResponse || networkResponse.status !== 200 || networkResponse.type !== 'basic') {
          return networkResponse;
        }

        const responseToCache = networkResponse.clone();
        caches.open(CACHE_NAME_RHB).then((cache) => {
          cache.put(event.request, responseToCache);
        });

        return networkResponse;
      });
    })
  );
});

// Comunicación con el cliente para obtener la versión
self.addEventListener('message', (event) => {
  if (event.data === 'GET_VERSION') {
    event.source.postMessage({ version: CACHE_NAME_RHB });
  }
});

