/* Service Worker */

const appVersion = "0.0.1-dev-20230127001"
const cacheName = `owlboard-${appVersion}`
const cacheIDs = [cacheName]
const cacheFiles = [
    "/404.html",
    "/conn-err.html",
    "/help.html",
    "/",
    "/issue.html",
    "/settings.html",
    "/manifest.json",
    "/styles/fonts/firamono/firamono-500.woff2",
    "/styles/fonts/firamono/firamono-regular.woff2",
    "/styles/fonts/urwgothic/urwgothic.woff2",
    "/styles/fonts/urwgothic/urwgothicDemi.woff2",
    "/styles/boards.css",
    "/styles/find-code.css",
    "/styles/help.css",
    "/styles/main.css",
    "/styles/settings.css",
    "/js/find-code.js",
    "/js/index.js",
    "/js/lib.board.js",
    "/js/lib.main.js",
    "/js/settings.js",
    "/js/simple-board.js",
    "/images/icon.svg",
    "/images/logo/wide_logo.svg",
    "/images/logo/mono-logo.svg",
    "/images/nav/alert_icon.svg",
    "/images/nav/save.svg",
    "/images/nav/home_icon.svg",
    "/images/nre/nre-powered_200w.webp"
]

self.addEventListener("install", (e) => {
    console.log("[Service Worker] Install");
    e.waitUntil(
        (async () => {
            const cache = await caches.open(cacheName);
            console.log("[Service Worker] Caching app data");
            await cache.addAll(cacheFiles);
        })()
    );
  });

  self.addEventListener("fetch", (e) => {
    e.respondWith(
      (async () => {
        const r = await caches.match(e.request);
        if (r) {
          return r;
        }
        const response = await fetch(e.request);
        console.log(`[Service Worker] Not cached - fetching from server: ${e.request.url}`);
        return response;
      })()
    );
  });

  self.addEventListener('activate', function (event) {
    event.waitUntil(caches.keys().then(function (keys) {
      return Promise.all(keys.filter(function (key) {
        return !cacheIDs.includes(key);
      }).map(function (key) {
        return caches.delete(key);
      }));
    }).then(function () {
      return self.clients.claim();
    }));
  });