importScripts('/scripts/sw/workbox/workbox-sw.js');

workbox.setConfig({
    modulePathPrefix: '/scripts/sw/workbox/'
  });
workbox.skipWaiting();
workbox.clientsClaim(); 

workbox.precaching.precacheAndRoute([]);

// cache images
workbox.routing.registerRoute(
    /\.(?:png|PNG|gif|GIF|jpg|JPG|jpeg|JPEG|svg|SVG)$/,
    workbox.strategies.cacheFirst({
        cacheName: 'images',
        plugins: [
        new workbox.expiration.Plugin({
            maxEntries: 60,
            maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
        }),
        ],
    }),
);

// cache giphy
workbox.routing.registerRoute(
  'https://media.giphy.com/media/3oz8xBkRsgPTnbK1GM/giphy.gif',
  workbox.strategies.staleWhileRevalidate()  
);

// cache pages for one hour
workbox.routing.registerRoute(
    /\/(dashboard|news|courses)\/$/,
    workbox.strategies.networkFirst({
        cacheName: 'pages',
        maxAgeSeconds: 60 * 60,
        networkTimeoutSeconds: 3,
        plugins: [
            new workbox.expiration.Plugin({
              maxEntries: 50,
              maxAgeSeconds: 60 * 60, 
            }),
            new workbox.cacheableResponse.Plugin({
              statuses: [0, 200],
            }),
          ],
    })
);

const queue = new workbox.backgroundSync.Queue('logsQueue');

function customHeaderRequestFetch(event) {
    return new Promise((resolve, reject) =>{
        event.request.blob().then(blob =>{
            const newRequest = new Request(event.request.url, {
                headers: {
                    'sw-enabled': true
                },
                method: 'POST',
                body: blob
            });
            resolve(fetch(newRequest.clone()) | queue.addRequest(newRequest));
        });
    });
}

self.addEventListener('fetch', event => {
    if (event.request.url.endsWith('/logs/')){
        event.respondWith(customHeaderRequestFetch(event));
    }
});

// calendar events
// https://developers.google.com/web/tools/workbox/modules/workbox-broadcast-cache-update
workbox.routing.registerRoute(
    '/calendar/events/',
    workbox.strategies.staleWhileRevalidate({
        plugins: [
            new workbox.broadcastUpdate.Plugin('event-updates')
        ]
    })
);

@@ -1268,21 +1268,16 @@
 ue('logs
-Queue
 ');%0A%0Afun
@@ -1316,16 +1316,36 @@
 vent) %7B%0A
+    let newRequest;%0A
     retu
@@ -1379,16 +1379,17 @@
 ject) =%3E
+ 
 %7B%0A      
@@ -1423,16 +1423,17 @@
 (blob =%3E
+ 
 %7B%0A      
@@ -1438,22 +1438,16 @@
         
-const 
 newReque
@@ -1693,39 +1693,208 @@
 e())
- %7C queue.addRequest(newRequest)
+%0A            .catch(_ =%3E%0A                queue.addRequest(newRequest)%0A                    .then(_ =%3E%0A                        new Response('cached')%0A                    )%0A                )%0A            
 );%0A 

send response on cache