self.addEventListener("install", (event) => {
    console.log("Service worker installing...");
    event.waitUntil(
        caches.open("snek-cache").then((cache) => {
            return cache.addAll([]);
        })
    );
})

self.addEventListener("activate", (event) => {
  event.waitUntil(self.registration?.navigationPreload.enable());
});

self.addEventListener("push", (event) => {
    if (!self.Notification || self.Notification.permission !== "granted") {
        console.log("Notification permission not granted");
        return;
    }

    const data = event.data?.json() ?? {};
    console.log("Received a push message", event, data);

    const title = data.title || "Something Has Happened";
    const message =
        data.message || "Here's something you might want to check out.";
    const icon = data.icon || "/image/snek512.png";

    const notificationSettings = data.notificationSettings || {};

    console.log("Showing message", title, message, icon);

    const reg = self.registration.showNotification(title, {
        body: message,
        tag: "message-received",
        icon,
        badge: icon,
        ...notificationSettings,
        data,
    }).then(e => console.log("Showing notification", e)).catch(console.error);

    event.waitUntil(reg);
});

self.addEventListener("notificationclick", (event) => {
    console.log("Notification click Received.", event);
    event.notification.close();
    event.waitUntil(clients.openWindow(`${event.notification.data.url || event.notification.data.link || `/web.html`}`));
});

self.addEventListener("notificationclose", (event) => {
    console.log("Notification closed", event);
})

self.addEventListener("fetch", (event) => {
    event.respondWith(
        caches.match(event.request).then((response) => {
            if (response) {
                // console.log("Found response in cache: ", response);
                return response;
            }
            return fetch(event.request);
        })
    );
})
