const CACHE_NAME_IAS = 'sefia-v3.2.3'; //self.APP_VERSION_IAS;
console.log(CACHE_NAME_IAS); // Esto imprimirá el nombre del caché con la fecha formateada
const urlsToCacheIas = [
  'index.html',
  'open.html',
  'openvideo.html',
  'newpdf.html',
  'adherencia.html',
  'manifest.json',
  'ejechart.html',
  'imgchart.html',
  'encuestaplus.html',
  'encuesta.html',
  'encuestalite.html',
  'settings.html',
  'js/index.js',
  'js/jssetup.js',
  'js/vision_bundle.js',
  'js/vision_wasm_internal.js',
  'js/hand_landmarker.task',
  'js/vision_wasm_internal.wasm',
  'js/vision_wasm_nosimd_internal.js',
  'js/vision_wasm_nosimd_internal.wasm',
  'js/face_landmarker.task',
  'js/pose_landmarker_full.task',
  'js/pose_landmarker_lite.task',
  'js/mediapipe.js',
  'js/landmarks.js',
  'js/gesture_recognizer.task'
  /*,
  '../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_IAS).then(cache => cache.addAll(urlsToCacheIas))
      .then(() => self.skipWaiting())
  );
});

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

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

// 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_IAS).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_IAS });
  }
});
