export const registerServiceWorker = async (silent = false) => {
    try {
        const serviceWorkerRegistration = await navigator.serviceWorker
            .register("/service-worker.js")

        await serviceWorkerRegistration.update()

        await navigator.serviceWorker.ready

        const keyResponse = await fetch('/push.json')
        const keyData = await keyResponse.json()

        const publicKey = Uint8Array.from(atob(keyData.publicKey), c => c.charCodeAt(0))

        const pushSubscription = await serviceWorkerRegistration.pushManager.subscribe({
            userVisibleOnly: true, applicationServerKey: publicKey,
        })

        const subscriptionObject = {
            ...pushSubscription.toJSON(), encoding: PushManager.supportedContentEncodings,
        };
        console.log(pushSubscription.endpoint, pushSubscription, pushSubscription.toJSON(), subscriptionObject);

        const response = await fetch('/push.json', {
            method: 'POST', headers: {
                'Content-Type': 'application/json',
            }, body: JSON.stringify(subscriptionObject),
        })

        if (!response.ok) {
            throw new Error('Bad status code from server.');
        }

        const responseData = await response.json();
        console.log('Registration response', responseData);
    } catch (error) {
        console.error("Error registering service worker:", error);
        if (!silent) {
            alert("Registering push notifications failed. Please check your browser settings and try again.\n\n" + error);
        }
    }
}


window.registerNotificationsServiceWorker = () => {
    return Notification.requestPermission().then((permission) => {
        if (permission === "granted") {
            console.log("Permission was granted");
            return registerServiceWorker();
        } else if (permission === "denied") {
            console.log("Permission was denied");
        } else {
            console.log("Permission was dismissed");
        }
    });
};
registerServiceWorker(true).catch(console.error);
