importScripts('./ngsw-worker.js');

// FIREBASE PART:
if (ServiceWorkerRegistration && "pushManager" in ServiceWorkerRegistration.prototype) {
    importScripts(
        "https://www.gstatic.com/firebasejs/10.12.4/firebase-app-compat.js",
    );
    importScripts(
        "https://www.gstatic.com/firebasejs/10.12.4/firebase-messaging-compat.js",
    );

    firebase.initializeApp({
        apiKey: "AIzaSyB9ImzI3ESfQk8mkgaWfmPd6b06djc6Toc",
        authDomain: "unibersereataurent.firebaseapp.com",
        projectId: "unibersereataurent",
        storageBucket: "unibersereataurent.appspot.com",
        messagingSenderId: "1001398873026",
        appId: "1:1001398873026:web:eb8554d5083ddcd28d845b",
        vapidKey: "BGDEauE5WfSMqA2Bi49wzOQyURiAe7-KP3e3VotUSgLmNk-mScvRhemqZ4mc26pVrwvFPLKVBsL35ikLcB3IvXk"
    });
    const messaging = firebase.messaging();

    messaging.onBackgroundMessage(async (payload) => {
        console.log('Received background message ', payload);
        const notificationTitle = payload.notification.title;
        const notificationOptions = {
        body: payload.notification.body,
        };
        const clientList = await clients.matchAll({
            type: 'window',
            includeUncontrolled: true
          });
      
          const isClientFocused = clientList.some(client => client.focused);
      
          if (!isClientFocused) {
            self.registration.showNotification(notificationTitle, notificationOptions);
           }
    });


    self.addEventListener('notificationclick', (event) => {
        event.notification.close(); // Close the notification
        console.log('click eventfrom service worker',event)
        // console.log('click eventfrom service worker',window.document)
        // Perform actions based on the notification data
        // const url = event.notification.data?.url || '/'; // Default URL if not provided

        // let url = 'http://localhost:4200/';
        // event.waitUntil(
        //     clients.matchAll({type: 'window'}).then( windowClients => {
        //         // Check if there is already a window/tab open with the target URL
        //         for (var i = 0; i < windowClients.length; i++) {
        //             var client = windowClients[i];
        //             console.log("client log",client)
        //             // If so, just focus it.
        //             if (client.url === url && 'focus' in client) {
        //                 return client.focus();
        //             }
        //         }
        //         // If not, then open the target URL in a new window/tab.
        //         if (clients.openWindow) {
        //             return clients.openWindow(url);
        //         }
        //     })
        // );

        event.waitUntil(
            clients.matchAll({ type: 'window', includeUncontrolled: true }).then(windowClients => {
                for (let i = 0; i < windowClients.length; i++) {
                    const client = windowClients[i];
                    console.log("client log", client);
                    // Focus the window if it's open
                    // if (client.focus) {
                    //     client.focus();
                    // }
                    // let targetUrl  = 
                    // Send a message to the client to change the URL
                    console.log("postmessage event", event);
                    // client.postMessage({
                    //     ...event.notification.data, // Include original data
                    //     type: 'NAVIGATE',
                    //     // url: targetUrl
                    // });
                    return;
                }
            })
        );
    });
}
