"use strict";

const version = "0.1.2";
const repo = "loorisvalf";
const name = "sound-meter";
const cdn = "cdn.jsdelivr.net";
const root = "pwa/build/index.html";
const worker = "pwa/build/worker.js";

const body = async ({ request }) => {
  let { url } = request;
  if (url.indexOf(root + "?") !== -1) url = url.split("?")[0];
  /*  */
  const cache = await caches.open(name);
  let response = await cache.match(url);
  if (response) return response;
  /*  */
  try {
    const a = url.indexOf("favicon") !== -1;
    const b = url.indexOf("/pwa/build") === -1 && url.indexOf(cdn) === -1;
    if (a || b) return await fetch(url);
    /*  */
    if ([root, worker].some((s) => url.indexOf(s) !== -1)) {
      response = await fetch(request);
    } else {
      const postfix = url.split("pwa/build/")[1];
      if (postfix) {
        const path =
          "https://" +
          cdn +
          "/gh/" +
          repo +
          "/" +
          name +
          "@" +
          version +
          "/data/interface/" +
          postfix;
        response = await fetch(path);
      } else {
        response = await fetch(url);
      }
    }
    /*  */
    if (response.ok) {
      cache.put(request, response.clone());
    }
  } catch (e) {
    return new Response("", {
      status: "404",
      statusText: "Cannot fetch resource: " + e.message,
    });
  }
  /*  */
  return response;
};

self.addEventListener("install", () => self.skipWaiting());
self.addEventListener("fetch", (e) => e.respondWith(body(e)));
self.addEventListener("activate", () => self.clients.claim());
