/*
 * Copyright 2008-2009 Palm, Inc. All rights reserved.
 */

/**
 * Constructor.
 */
function BrowserPrefsStore() {
	this._onErrorHandler = this._onError.bind(this);
	this._depotParams = {name: Browser.Database.name, version: Browser.Database.version};
}

/**
 * Called when the preferences object has been successfully read from the depot.
 * 
 * @param {BrowserPrefs} A browser preferences object.
 */
BrowserPrefsStore.prototype._loadReadSuccess = function(prefs) {

	if (prefs) {
		
		if (prefs.EnableJavaScript !== undefined) {
			this.prefs.EnableJavaScript = prefs.EnableJavaScript;
		}
		if (prefs.BlockPopups !== undefined) {
			this.prefs.BlockPopups = prefs.BlockPopups;
		}
		if (prefs.AcceptCookies !== undefined) {
			this.prefs.AcceptCookies = prefs.AcceptCookies;
		}

		if (prefs.ClearCache !== undefined) {
			this.prefs.ClearCache = prefs.ClearCache;
		}
		if (prefs.ClearHistory !== undefined) {
			this.prefs.ClearHistory = prefs.ClearHistory;
		}
		if (prefs.ClearCookies !== undefined) {
			this.prefs.ClearCookies = prefs.ClearCookies;
		}
	}

	this.onSuccess();
	
	this._cleanup();
};

BrowserPrefsStore.prototype._cleanup = function() {
	delete this.depot;
	delete this.prefs;
	delete this.onSuccess;
};

BrowserPrefsStore.prototype._onError = function(param) {
	Mojo.Log.error("ERROR reading/writing to browser depot: %s", Object.toJSON(param));
	this._cleanup();
};

/**
 * Preferences database successfully opened.
 */
BrowserPrefsStore.prototype._loadOpenSuccess = function() {
	this.depot.simpleGet('preferences', 
		this._loadReadSuccess.bind(this), this._onErrorHandler );
};

/**
 * Create or open the browser preferrences.
 */
BrowserPrefsStore.prototype.load = function(prefs, onSuccess) {
	this.prefs = prefs;
	this.onSuccess = onSuccess;
	this.depot = new Mojo.Depot(this._depotParams,
		this._loadOpenSuccess.bind(this), this._onErrorHandler );
};

/**
 * Preferences database successfully opened.
 */
BrowserPrefsStore.prototype._saveOpenSuccess = function() {

	this.depot.simpleAdd('preferences', this.prefs,
		function() {
			this._cleanup();
		}.bind(this), this._onErrorHandler );
};

/**
 * Create or open the browser preferrences.
 */
BrowserPrefsStore.prototype.save = function(prefs) {
	this.prefs = prefs;
	this.depot = new Mojo.Depot(this._depotParams,
		this._saveOpenSuccess.bind(this), this._onErrorHandler	);
};

