/**
 * Service Worker to handles nnatives broser caches for offline cap and PWA install
 */
const cacheName = "fp01a";

const appDir = location.hostname == 'devignia.site' ? '/fruitpick' : '/fruitpick/src';

const filesList = [
	"/",
	// "browserconfig.xml", // IE11 icon configuration file
	"/icons/favicon.svg",
	"/splash.png",
	"/icons/favicon-96x96.png", // Favicon, default
	"/index.html", // Main HTML file
	"/onboarding.html", // Onboarding english file
	"/privacy-en.html", // Privacy english
	"/privacy-es.html", // Privacy spanish
	"/site.webmanifest", // Manifest file
	"/css/game.min.css", // Main CSS file
	
	// JS builds only
	"/js/vendors.min.js",
	"/js/game.min.js",
	"/js/guest.min.js",
	
];

// Prepend dir entries with install dirname
filesList.forEach((item, key) => {
	 filesList[key] = appDir + item;
});

/**
 * No need to edit from here
 * 
 * Dragons, mandragoras, mythical creatures ahead...
 */

self.addEventListener("install", event => {
	// Kick out the old service worker
	self.skipWaiting();
	
	event.waitUntil(
		caches.open(cacheName).then(cache => {
			return cache.addAll(filesList);
		}).then(() => self.postMessage('installed!')).catch(console.log)
	);
});

self.addEventListener("activate", event => {
	// Delete any non-current cache
	event.waitUntil(
		caches.keys().then(keys => {
			Promise.all(
				keys.map(key => {
					if (![cacheName].includes(key)) {
						return caches.delete(key);
					}
				})
			)
		})
	);
});

// Offline-first, cache-first strategy
// Kick off two asynchronous requests, one to the cache and one to the network
// If there's a cached version available, use it, but fetch an update for next time.
// Gets data on screen as quickly as possible, then updates once the network has returned the latest data. 
self.addEventListener("fetch", event => {
	event.respondWith(
		caches.open(cacheName).then(cache => {
			return cache.match(event.request).then(response => {
				return response || fetch(event.request)
					.then(networkResponse => {
						cache.put(event.request,
							networkResponse
							.clone());
						return networkResponse;
					});
			})
		})
	);
});
