/// <reference types="@sveltejs/kit" />

import { build, files, version } from "$service-worker";

const cacheName = `ob-${version}`;

const assets = [...build, ...files, "/service-worker.js"];

const excludePatterns = [
    "/static/images/screnshots",
    "/images/screenshots",
    "/static/images/shortcuts",
    "/images/shortcuts",
];

self.addEventListener("install", (event) => {
    async function addToCache() {
        const cache = await caches.open(cacheName);
        const assetsToCache = assets.filter(asset => {
            return !excludePatterns.some(pattern => asset.startsWith(pattern));
        });
        await cache.addAll(assetsToCache);
    }

    event.waitUntil(addToCache());
});

self.addEventListener("activate", (event) => {
    async function deleteOldCache() {
        for (const key of await caches.keys()) {
            if (key !== cacheName) {
                await caches.delete(key);
            }
        }
    }

    event.waitUntil(deleteOldCache());
});

self.addEventListener("fetch", (event) => {
    if (event.request.method !== "GET") {
        return;
    }
    async function respond() {
        const cacheRes = await caches.match(event.request, { ignoreSearch: true });
        if (cacheRes) {
            return cacheRes;
        }

        try {
            return await fetch(event.request);
        } catch (err) {
            return { error: "OFFLINE", errorMsg: "You are offline" };
        }
    }

    event.respondWith(respond());
});
