const DB_NAME		= 'sable_cc';
const DB_VERSION	= '1.0';

var sableDB			= null;
var sableStore		= null;
var sableInfoPrefix = "[SableDB] ";
var sableTableName	= "sable";
var sableKeyName	= "sableID";

//*** DB Operations ***//
 
sableCreateDB = function()
{
	var request				= self.indexedDB.open(DB_NAME, DB_VERSION);		
	request.onerror			= sableRequestOnError;		
	request.onsuccess		= sableRequestOnSuccess;
	request.onupgradeneeded	= sableRequestOnUpgradeNeeded;	
}

sableRequestOnError = function(event)
{
	console.error(sableInfoPrefix + "Failed to create DB "+DB_NAME+".");
}

sableRequestOnSuccess = function(event)
{
	if (event.target.result){sableDB = event.target.result;}		
}

sableRequestOnUpgradeNeeded = function(event)
{
	if (event.target.result){sableDB = event.target.result;};
	sableCreateTable();
	//console.log(sableDB);
	//console.info(sableInfoPrefix, "Upgrade needed - updated.");	
}

sableCreateTable = function()
{
	sableStore = sableDB.createObjectStore(sableTableName, {keyPath: sableKeyName});
	//console.log(sableStore);
	sableStore.onerror = function(event)
	{
		console.error(sableInfoPrefix + "Failed to create table "+sableTableName+".");
	};
	//console.info(sableInfoPrefix, "Table "+sableTableName+" successfully created.");	

	if (typeof getSableData === "function")
	{
		var sableData = getSableData(); //this function is provided from the backend.. don't remove!! 
		for (var i in sableData){sableStore.add(sableData[i]);}	
	}
}

sableAddRow = function(mode, data) 
{
	//console.log(sableDB);
	var request = sableDB.transaction([sableTableName], mode).objectStore(sableTableName).add(data);
	//var request = sableStore.add(data);
	
	request.onsuccess = function(event) 
	{
		console.info(sableInfoPrefix, "The record was successfully added.");
	};
	
	request.onerror = function(event) 
	{
		console.error(sableInfoPrefix, "The record failed to add.");
	}
};

sableReadRow = function(id, callback) 
{
	var transaction = sableDB.transaction([sableTableName]);
	var objectStore = transaction.objectStore(sableTableName);
	var request = objectStore.get(id);
	
	request.onerror = function(event)
	{
		console.error(sableInfoPrefix + "The database cannot be accessed and may not yet exist.");
	};
	
	request.onsuccess = function(event) 
	{
		if (request.result) 
		{
			console.info(sableInfoPrefix, request.result);
			if (request.result !== undefined) callback(request.result);
			//return request.result;
		} 
		else 
		{
			console.error(sableInfoPrefix + "No data found  for id "+id+" from table "+sableTableName+".");  
		}
	};
};

sableReadAll = function()
{
	var objectStore = sableDB.transaction(sableTableName).objectStore(sableTableName);
	
	objectStore.openCursor().onsuccess = function(event) 
	{
		var cursor = event.target.result;
		if (cursor)
		{
			console.info(sableInfoPrefix,	"Data for id " + cursor.key + ": " + cursor.value);
			cursor.continue();
		} 
		else
		{
			console.info(sableInfoPrefix, "Read finished.");
		}
	};
};

function getKeyByValue(object, field, value) 
{
	for (var prop in object) 
	{
		if (object.hasOwnProperty(field)) 
		{
			if (object[prop] === value) 
			{
				return prop; //record found. 
			}
		}
	} 
}

function getKeyByTable(object, table) 
{
	var res = 0;
	for (var prop in object) 
	{
		if (object.hasOwnProperty('table')) 
		{
			if (object['table'] === table) 
			{
				res = 1; //record found.
			}
		} 
		break;
	}
	return res;
}

sableGetRows = function(table, callback)
{
	if (sableDB === null) return;
	
	try
	{
		var objectStore = sableDB.transaction(sableTableName).objectStore(sableTableName);
	}
	catch(err)
	{
		console.error(err.message);
		return;
	}
	
	var res = null, sableRows = [];
	
	objectStore.openCursor().onsuccess = function(event) 
	{
		var cursor = event.target.result;
		if (cursor)
		{
			res = getKeyByTable(cursor.value, table);
			if (res)
			{
				sableRows.push(cursor.value);
			}
			cursor.continue();
		} else callback(sableRows);
	};
};

sableFindRow = function(field, value, callback)
{
	var objectStore = sableDB.transaction(sableTableName).objectStore(sableTableName);
	var key = null;
	var data = null;
	
	objectStore.openCursor().onsuccess = function(event) 
	{
		var cursor = event.target.result;
		if (cursor)
		{
			key = cursor.key;
			data = getKeyByValue(cursor.value, field, value);
			if (data === undefined)
			{ 
				cursor.continue(); 
			}
			else 
			{
				if (callback) callback(cursor.value); //record found.
				return;
			}
		} 
		else
		{
			//if (callback) callback(); 
			return false; //no data
		}
	};
};

sableFindRows = function(field, value, callback)
{
	var objectStore = sableDB.transaction(sableTableName).objectStore(sableTableName);
	var key = null;
	var data = [];
	
	objectStore.openCursor().onsuccess = function(event) 
	{
		var cursor = event.target.result;
		if (cursor)
		{
			key = cursor.key;
			data = getKeyByValue(cursor.value, field, value);
			if (data !== undefined){data.push(cursor.value);}
			cursor.continue();
		}
		callback(data);
	}
}

sableRemoveRow = function(mode, id, callback) 
{
	var request = sableDB.transaction([sableTableName], mode).objectStore(sableTableName).delete(id);
	request.onsuccess = function(event) 
	{
		//console.log(sableInfoPrefix, "Record with key "+id+" successfully deleted from table "+sableTableName);
		if (callback) callback();
	};
}

/**window = self **/
self.indexedDB		= self.indexedDB		|| self.mozIndexedDB 			|| self.webkitIndexedDB 	|| self.msIndexedDB;
self.IDBTransaction	= self.IDBTransaction	|| self.webkitIDBTransaction 	|| self.msIDBTransaction;
self.IDBKeyRange	= self.IDBKeyRange 		|| self.webkitIDBKeyRange 		|| self.msIDBKeyRange;
 
if (!self.indexedDB) 
{
   self.alert("Your browser doesn't support a stable version of IndexedDB.")
}
else
{
	sableCreateDB();	
}

function redirectToOfflineLogin()
{
	//console.info('redirecting to offline login page...');
	self.location = '/app/offline.html';
}

function redirectToOnlineLogin()
{
	//console.info('redirecting to online login page...');
	self.location = '/';
}

self.addEventListener('offline',	redirectToOfflineLogin);
//self.addEventListener('online',	redirectToOnlineLogin);