const cacheName = 'cache-v1';
const precacheResources = [
    'otpreq.php'
];

self.addEventListener('install', event => {
    event.waitUntil(
        caches.open(cacheName)
            .then(cache => {
                return cache.addAll(precacheResources);
            })
    );
});

self.addEventListener('activate', event => {
    // delete any caches that aren't in cacheName
    // which will get rid of static-v1
    event.waitUntil(
        caches.keys().then(keys => Promise.all(
            keys.map(key => {
                if (!cacheName.includes(key)) {
                    return caches.delete(key);
                }
            })
        )).then(() => {
            console.log( cacheName + ' now ready to handle fetches!');
        })
    );
});

self.addEventListener('message', event => {
    if (!event.data) {
        return;
    }

    if (event.data === 'SKIP_WAITING') {
        self.skipWaiting();
    }
});

self.addEventListener('fetch', event => {
    event.respondWith(caches.match(event.request)
        .then(cachedResponse => {
            // if (cachedResponse) {
            //     return cachedResponse;
            // }
            return fetch(event.request);
        })
    );
});