/**
 * Provide the interaction between the camera app and the preferences it has stored 
 * in the HTML 5 database.
 * 
 
Copyright 2009 Palm, Inc.  All rights reserved.

*/


CameraPrefs = {
	_isLoaded: false,
	_prefs: {},

	/**
	 * Function to be called the check that the preferences have been loaded
	 * 
	 * @return {Boolean}  true if preferences are already loaded 
	 */
	isLoaded: function(){
		return CameraPrefs._isLoaded;
	},
	
	loadPrefs: function(loadedCallback) {
		llog("Entering loadPrefs");
		CameraPrefs._prefs = CameraPrefs._getDefaultPrefs();
		var cookie;
		var value;

		for (var key in CameraControl.PREFS){
			//llog("key: "+key);
			cookie = new Mojo.Model.Cookie(key);
			value = cookie.get();
			if (value) {
				CameraPrefs._prefs[key] = value;
			//llog("Loaded cookie: "+key+" "+CameraPrefs._prefs[key]);
			}
			
		}

		CameraPrefs._isLoaded = true;
		
		if (loadedCallback){
			loadedCallback(true, CameraPrefs._prefs);
		}	
	},


	/**
	 * Used to update a single value in the database
	 * @param {String} key  The field to updated.  Must be one of the CameraControl.PREFS.XXX fields
	 * @param {String} val  The value to assign to the key.  Must be a string.
	 */
	updatePref: function(prefHash, key, val){

		if (typeof(val) == 'number'){
			val = ""+val;
		}

		llog("update pref: "+key+": "+val);
		prefHash[key] = val;
		
		var cookie = new Mojo.Model.Cookie(key);
		cookie.put(val);
	},

	
	/**
	 * Create a set of default preferences.  Called if there (a) are no prefs in the DB or (b)
	 * if there is a problem reading/creating the database table/entries.
	 * 
	 * @return {Object} A hash of preferences as defined in CameraControl.PREFS
	 *
	 * @private
	 */
	_getDefaultPrefs: function(){
		if (undefined === window.CameraPrefsDefaultPrefs) {
			var fileText = palmGetResource(Mojo.appPath+"camera-prefs-defaults.json");
			CameraPrefsDefaultPrefs = JSON.parse(fileText);
		}

		return CameraPrefsDefaultPrefs;
	}
};



 