const CACHE_NAME = 'pinpalin-offline-v6';
const APP_SHELL = [
  "./header.jpg",
  "./icons/icon-192.png",
  "./icons/icon-512.png",
  "./images/Arbolesa.png",
  "./images/Arbolesb.png",
  "./images/NubesA.png",
  "./images/NubesB.png",
  "./images/Plano01a.png",
  "./images/Plano01b.png",
  "./images/Plano02a.png",
  "./images/Plano02b.png",
  "./images/Plano03a.png",
  "./images/Plano03b.png",
  "./images/Plano04a.png",
  "./images/Plano04b.png",
  "./images/abeja.png",
  "./images/back.png",
  "./images/h1.png",
  "./images/h2.png",
  "./images/h3.png",
  "./images/hojas 1.png",
  "./images/hojas 2.png",
  "./images/hojas 3.png",
  "./images/hojas 4.png",
  "./images/hormigas.png",
  "./images/mariposa.png",
  "./images/n1.png",
  "./images/n2.png",
  "./images/next.png",
  "./images/ninos.png",
  "./images/p1.png",
  "./images/p2.png",
  "./images/p3.png",
  "./images/p4.png",
  "./images/paloma.png",
  "./images/perro.png",
  "./images/rana.png",
  "./images/sol.png",
  "./index.html",
  "./app.html",
  "./info.html",
  "./libs/lame.min.js",
  "./manifest.json",
  "./sounds/abeja.mp3",
  "./sounds/abejab.mp3",
  "./sounds/h1.mp3",
  "./sounds/h1b.mp3",
  "./sounds/h2.mp3",
  "./sounds/h2b.mp3",
  "./sounds/h3.mp3",
  "./sounds/h3b.mp3",
  "./sounds/mariposa.mp3",
  "./sounds/mariposab.mp3",
  "./sounds/n1.mp3",
  "./sounds/n1b.mp3",
  "./sounds/n2.mp3",
  "./sounds/n2b.mp3",
  "./sounds/p1.mp3",
  "./sounds/p1b.mp3",
  "./sounds/p2.mp3",
  "./sounds/p2b.mp3",
  "./sounds/p3.mp3",
  "./sounds/p3b.mp3",
  "./sounds/p4.mp3",
  "./sounds/p4b.mp3",
  "./sounds/paloma.mp3",
  "./sounds/palomab.mp3",
  "./sounds/perro.mp3",
  "./sounds/perrob.mp3",
  "./sounds/rana.mp3",
  "./sounds/ranab.mp3",
  "./sounds/sol.mp3",
  "./sounds/solb.mp3"
];

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

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

self.addEventListener('fetch', (event) => {
  if (event.request.method !== 'GET') return;
  event.respondWith(
    caches.match(event.request).then((cached) => {
      if (cached) return cached;
      return fetch(event.request).then((response) => {
        const copy = response.clone();
        caches.open(CACHE_NAME).then((cache) => cache.put(event.request, copy));
        return response;
      }).catch(() => caches.match('./index.html'));
    })
  );
});
