const OFFLINE_URL	= '/themes/sable/offline/offline.html';
const OFFLINE_JS	= '/themes/sable/offline/offline.js';
const IDB_JS		= '/scripts/sable_db.js';
const NOTIF_BADGE	= '/media/images/notification_badge.png';
const NOTIF_LOGO	= '/media/images/manifest_logo.png';

importScripts(IDB_JS, OFFLINE_JS);
//const DB_NAME		= 'sable_lubeng';

const CACHE_VERSION = '1';
const CACHE_NAME	= DB_NAME+'_'+CACHE_VERSION;
const CACHE_FILES = [
	'/media/fonts/bootstrap_3.3.7/glyphicons-halflings-regular.woff2',
	'/media/fonts/fa-brands-400.woff2',
	'/media/fonts/fa-regular-400.woff2',
	'/media/fonts/fa-solid-900.woff2',//------
	'/themes/sable/img/logos/logo_sm.png',
	'/media/images/DropDownArrow.png',
	'/media/images/email_logo.png',
	'/media/images/logo_md.jpg',	
	NOTIF_LOGO,
	NOTIF_BADGE,
	'/media/images/ogLogo.jpg',
	'/media/images/unknown_image.png',
	'/media/images/wait_load.gif',//------
	'/scripts/jquery-2.1.4.min.js',
	'/scripts/sable.js',
	IDB_JS,
	'/scripts/bootstrap_3.3.7/bootstrap.min.js',//------
	'/style/bootstrap_3.3.7/bootstrap.min.css',
	'/style/all.min.css',//------
    '/themes/sable/css/custom.css',
	'/themes/sable/css/main.css',
	'/themes/sable/css/sable.css',//------
	'/themes/sable/img/logos/logo_sm.png',
	'/themes/sable/img/apple_touch_logo.png',
	'/themes/sable/img/msapp_logo.png',
	'/themes/sable/img/favicon.png',//------
	'/themes/sable/js/vendors/wow/wow.min.js',
	'/themes/sable/js/jquery.main.js',
	OFFLINE_JS,
	OFFLINE_URL,
	'/themes/sable/offline/offline.html',
	'/manifest.json',
	'sw.js'
];

self.inspectionRec = null;

self.addEventListener
('install', 
	function(event) 
	{
		var offlineRequest = new Request(OFFLINE_URL);
		event.waitUntil
		(
			fetch(offlineRequest).then
			(
				function(response)
				{
					return caches.open(CACHE_NAME).then
					(
						function(cache)
						{
							cache.addAll(CACHE_FILES)
							.then(self.skipWaiting())
							.catch(err => console.error("[sw.js] Error trying to pre-fetch cache files:", err));							
							console.log('[oninstall] Cached offline page', response.url);
							return cache.put(offlineRequest, response);
						}
					);
				}
			)
		);
	}
);

self.addEventListener
('fetch', 
	function(event) 
	{
		var request = event.request;
		if (request.method === 'GET') 
		{
			event.respondWith
			(
      			fetch(request).catch
				(
					function(error)
					{
		  				console.info('[onfetch] No connection. Serving cached offline fallback ', error);
        				return caches.open(CACHE_NAME).then
						(
							function(cache)
							{
          						return cache.match(OFFLINE_URL);
        					}
						);
      				}
				)
    		);
  		}
  }
);


self.addEventListener
('sync', 
	function(event) 
	{
		console.log(event);
  		if (event.tag === 'sableBackgroundSync')
		{
    		event.waitUntil
			(
				 //May give an error initially on first load due to the non-existence of a database. Thereafter it will access the existing data.	 
				 sableGetRows('offline_inspections', postOfflineInspections)
			);
  		}
	}
);

function showNotification(result)
{
	navigator.serviceWorker.ready.then
	(
		function(registration)
		{
			registration.showNotification
			('Inspection Submitted',
				{
					body: 'Your offline inspection was successfully saved to the server.',
					icon: '/themes/sable/img/apple_touch_logo.png',
					vibrate: [200, 100, 200, 100, 200],
					tag: 'offline-inspection-conducted'
				}
			);
		}
	);
}

function updateUser()
{
	self.registration.showNotification
	('Inspection Submitted',
		{
			body:		'Your offline inspection was successfully saved to the server.',
			icon:		NOTIF_LOGO,
			badge:		NOTIF_BADGE,
			vibrate:	[200, 100, 200, 100, 200],
			tag:		'offline-inspection-conducted'
		}
	);
}

function sendData()
{
	var requestUrl = '/inspection/inspection_val.php';
	//var headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}; // if you have any other headers put them here
	var settings = {};
	
	console.log(self.inspectionRec);
	settings.headers	= {'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded'};
	settings.method		= 'POST';
	settings.body		= JSON.stringify(self.inspectionRec);
	
	fetch(requestUrl, settings).
	then
	(
		function (response) 
		{
			if (!response.ok)
			{
				throw Error(response.statusText);
			}
			if (response.status < 400) 
			{
				// If sending the POST request was successful, then remove it from the IndexedDB.
				sableRemoveRow("readwrite", self.inspectionRec.sableID, updateUser);
			}
		}
	);
}

function postOfflineInspections(recs)
{
	if (recs.length)
	{
		for (var i = 0; i < recs.length; i++)
		{
			self.inspectionRec = recs[i];
			sendData();
		}
	} else console.log('No cached records to process.');
}