// Template Name: Affan - PWA Mobile HTML Template
// Author: Designing World
// Author URL: https://themeforest.net/user/designing-world

const staticCacheName = 'cache-v10';
const dynamicCacheName = 'runtimeCache-v10';
const unCache = [
    '/export', '/lc', '/osc', '/token',
    'panel/bank-soal/example', 'login',
    'panel/bank-soal/example', 'logout',
    'panel/md/import/example', '/all',
    'panel/app/settings/backup-restore/backup',
    'panel/display/sync-attendance-solution',
    'panel/display/latestPresent',
    'panel/whatsapp'
];
// Pre Caching Assets
const precacheAssets = [
    'offline',
    'mobile/css/bootstrap.min.css',
    'mobile/img/core-img/dot-blue.png',
    'mobile/img/core-img/dot.png',
    'mobile/img/core-img/logo.png',
    'mobile/img/core-img/logo-dark.png',
    'mobile/img/core-img/favicon.ico',
    'mobile/js/active.js',
    'mobile/js/dark-rtl.js',
    'mobile/js/bootstrap.bundle.min.js',
    'mobile/js/pwa.js',
    'manifest.json',
    'mobile/style.css'
];

// Install Event
self.addEventListener('install', function (event) {
    event.waitUntil(
        caches.open(staticCacheName).then(function (cache) {
            return cache.addAll(precacheAssets);
        })
    );
});

// Activate Event
self.addEventListener('activate', function (event) {
    event.waitUntil(
        caches.keys().then(keys => {
            return Promise.all(keys
                .filter(key => key !== staticCacheName && key !== dynamicCacheName)
                .map(key => caches.delete(key))
            );
        })
    );
});

// fetch the resource from the network
const fromNetwork = (request, timeout) =>
    new Promise((fulfill, reject) => {
        const timeoutId = setTimeout(reject, timeout);
        fetch(request).then(response => {
            clearTimeout(timeoutId);
            update(request, response.clone());
            fulfill(response);
        }, reject);
    });

// fetch the resource from the browser cache
const fromCache = request =>
    caches
        .open(dynamicCacheName)
        .then(cache =>
            cache
                .match(request)
                .then(matching => matching || cache.match('/offline'))
        );

// cache the current page to make it available for offline
const update = (request, response) => {
    caches
        .open(dynamicCacheName)
        .then(cache => {
            if (response) {
                cache.put(request, response)
            } else {
                fetch(request).then(response => {
                    cache.put(request, response);
                });
            }
        }
        );
}

// Fetch Event
self.addEventListener('fetch', evt => {
    // disable event
    return;
    let forbidden = false;
    if (evt.request.method.toLowerCase() != 'get') return;
    for (let i = 0; i < unCache.length; i++) {
        if (evt.request.url.indexOf(unCache[i]) !== -1) {
            forbidden = true;
            return;
        }
    }
    if (forbidden) return;
    if (['style', 'script', 'image', 'font'].includes(evt.request.destination) && evt.request.url.indexOf('/offline') == -1) {
        evt.respondWith(
            caches.match(evt.request).then(cacheRes => {
                return cacheRes || fromNetwork(evt.request, 10000).catch(() => fromCache(evt.request))
            }).catch((err) => {
                return fromNetwork(evt.request, 10000).catch(() => fromCache(evt.request))
            })
        );
    } else {
        evt.respondWith(
            fromNetwork(evt.request, 10000).catch(() => fromCache(evt.request))
        );
    }
    evt.waitUntil(update(evt.request));
});

// NOT IMPORTANT
// self.addEventListener('fetch', function (event) {
//     // let unCache = ['/export', 'panel/bank-soal/example/zip', 'panel/bank-soal/example/excel', 'panel/md/import/example', 'panel/app/backup', '/panel', '/all', 'logout', 'login', '/soal/', '/config/'];
//     // let forbidden = false;
//     // for (let i = 0; i < unCache.length; i++) {
//     //     if (event.request.url.indexOf(unCache[i]) !== -1) {
//     //         forbidden = true;
//     //     }
//     // }
//     // if (forbidden) return false;
//     // if (event.request.destination == "") return false;
//     // if (event.request.mode == 'navigate' && event.request.redirect == 'manual') return false;
//     event.respondWith(
//         caches.match(event.request).then(cacheRes => {
//             return cacheRes || fetch(event.request).then(response => {

//                 return caches.open(dynamicCacheName).then(function (cache) {
//                     cache.put(event.request, response.clone());
//                     return response;
//                 })
//             });
//         }).catch(function () {
//             // Fallback Page, When No Internet Connection
//             return caches.match('offline');
//         })
//     );
// });