importScripts("precache-manifest.08172dfb2dfcdcf14d4acee76fc01cbb.js", "https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js");

let revisionTag = null;

self.addEventListener("activate", (event) => {
    revisionTag = null;
});

const hasTag = (url) => url.includes("?t=") || url.includes("revisionTag=");

self.addEventListener("fetch", (event) => {
    const url = event.request.url;
    if (url.includes("revisionTag=")) {
        revisionTag = url
            .split("?")[1]
            .split("&")
            .filter((v) => v.includes("revisionTag="))[0]
            .split("=")[1];
    }
    let taggedUrl;

    if (revisionTag !== null && !hasTag(url)) {
        taggedUrl = url + (url.includes("?") ? "&" : "?") + "t=" + revisionTag;
    } else {
        taggedUrl = url;
    }
    const taggedRequest = new Request(taggedUrl, {
        method: event.request.method,
        headers: event.request.headers,
        body: event.request.body,
        mode: event.request.mode === "navigate" ? "cors" : event.request.mode,
        credentials: event.request.credentials,
        redirect: event.request.redirect,
        referrer: event.request.referrer,
        integrity: event.request.integrity,
    });
    if (hasTag(taggedUrl) && taggedRequest.method === "GET") {
        event.respondWith(
            caches.open("Playa-cache").then((cache) =>
                cache.match(taggedRequest).then((response) => {
                    if (url.includes("revisionTag=")) {
                        return fetch(taggedRequest);
                    } else {
                        return (
                            response ||
                            fetch(taggedRequest).then((response) => {
                                cache.put(taggedRequest, response.clone());
                                return response;
                            })
                        );
                    }
                }),
            ),
        );
    } else {
        event.respondWith(fetch(event.request));
    }
});