'use strict';

// NOTE: StaticCacheName & FilesToCache list
const staticCacheName = 'omapp-v1.0.0';
const filesToCache = [
	'/',
	'/index.html',
	'/message.html',
	'/style.css',
	'/main.js',
	'/favicon.ico'
];

// NOTE: Registration done in main.js

// NOTE: Install and activate: Populating cache
self.addEventListener('install', function (event) {
	console.log('Service worker installing...');
	event.waitUntil(
		(console.log('Trying to install service worker and static cache files.'),
		caches.open(staticCacheName).then(function (cache) {
			return cache.addAll(filesToCache);
		}))
	);
});

// NOTE: Activate structure and delete older cache versions
self.addEventListener('activate', function (event) {
	console.log('Activating new service worker...');
	const cacheWhitelist = [staticCacheName];
	event.waitUntil(
		caches.keys().then(function (cacheNames) {
			return Promise.all(
				cacheNames.map(function (cacheName) {
					if (cacheWhitelist.indexOf(cacheName) === -1) {
						return caches.delete(cacheName);
					}
				})
			);
		})
	);
});


// NOTE: Fetch structure // TODO: Setup fetching method
self.addEventListener('fetch', function (event) {
	console.log('Fetch event for ', event.request.url);
	// Perform some task
});
