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

function AppAssistant(appController) {

	try {
		this.database = openDatabase(Browser.Database.name, Browser.Database.version, Browser.Database.displayName, Browser.Database.estimatedSize);
	}
	catch (e) {
		Mojo.Log.logException(e, "AppAssistant#AppAssistant: Database FAILED to open.");
	}
}

/**
 * Application wide help location
 */
AppAssistant.helpUrl = 'http://help.palm.com/web/index.html';
AppAssistant.noNetworkUrl = 'no-network';

AppAssistant.launchHelp = function() {

	// Launch the help system.
	var req = new Mojo.Service.Request('palm://com.palm.applicationManager', {
			method: 'open',
			parameters: {
				id: 'com.palm.app.help',
				params: {
					'target': AppAssistant.helpUrl
				}
			}
		});
};

AppAssistant.launchNetworkHelp = function() {
	
	// Launch the help system.
	var req = new Mojo.Service.Request('palm://com.palm.applicationManager', {
			method: 'open',
			parameters: {
				id: 'com.palm.app.help',
				params: {
					'target': AppAssistant.noNetworkUrl
				}
			}
		});	
};

AppAssistant.Network = new NetworkMonitor();

AppAssistant.prototype.setup = function() {

	AppAssistant.Network.observe(function(response){Mojo.Log.info("@@@ Listening to network events: online=", response.isInternetConnectionAvailable);});
};

AppAssistant.prototype.getDatabase = function() {

	return this.database;
};

AppAssistant.prototype.handleLaunch = function(params) {

	try {
		var launchParams = {};

		if (Object.isString(params)) {
			if (params.isJSON()) {
				launchParams = params.evalJSON();
			}
		}
		else {
			launchParams = params;
		}

		if (launchParams.defaultData) {
			this._processDefaultData(launchParams.defaultData);
			return;
		}

		// If we're headless, then we need to manually create a card stage.
		if (Mojo.Controller.appInfo.noWindow && !params.banner) {
			var stageName = "browser-" + Date.now();
			var f = function(stageController) {

				// Temporary code. The "url" property was renamed to "target"
				if (launchParams.url) {
					Mojo.Log.warn("WARNING: 'url' param deprecated; use 'target' instead!");
					launchParams.target = launchParams.url;
					delete launchParams.url;
				}

				// Sanitize the target property
				if (launchParams.target) {
					launchParams.target = launchParams.target.stripScripts().stripTags();
				}

				// Indicate this is a result of a launch.
				var pageParams = {
					launchParams: launchParams
				};
				
				// If we don't have a startup identifier nor URL we also push the startpage.
				if (!launchParams.target && !launchParams.pageIdentifier) {

					stageController.pushScene({
						name: 'startpage',
						transition: Mojo.Transition.crossFade
						},
						pageParams);

				} else {
					stageController.pushScene('page', pageParams);
				}
			};

			var imageName;
			if (launchParams.target || launchParams.pageIdentifier) {
			    imageName = 'images/splash-browser-page.png';
			} else {
			    imageName = 'images/splash-browser-startpage.png';
			}

			this.controller.createStageWithCallback({name: stageName, lightweight: true,
													 splashBackgroundName: imageName}, f);
		} else if(params.banner) {
			// This parameter is set when we're launched due to clicking our notification banner.
			// It causes us to switch to the notify scene.
			this.goToNotifyScene(params);
		}
	}
	catch (e) {
		Mojo.Log.logException(e, "AppAssistant#handleLaunch");
	}
};

AppAssistant.prototype.cleanup = function() {

};

AppAssistant.prototype.goToNotifyScene = function(params) {

	switch (params.banner) {
		
		case 'image':
			break;
			
		case 'download':
			break;
	}
	
};

AppAssistant.prototype._getCarrierNetworkSettings = function() {
	// Not yet called. Still coordinating with Ezekiel.
	try {
		var request = new Mojo.Service.Request('palm://com.palm.data.carriernetowrksettings/getUaProf', {
			parameters: {},
			onSuccess: function(error) {
			}.bind(this),
			onFailure: function(error) {
				Mojo.Log.error("Error getting carrier network settings. return %s, errorCode: %s, msg: '%s'", error.returnValue, error.errorCode, error.errorText);
			}.bind(this)
		});
	}
	catch (e) {
		Mojo.Log.logException(e, "_getCarrierNetworkSettings");
	}
};

AppAssistant.prototype._addDefaultBookmarks = function(defaultData) {

	try {
		if (defaultData && defaultData.bookmarks) {

			var folder = new BookmarkFolder('default');

			// Fixup the default bookmark data just in case any values were omitted.
			for (var i = 0; i < defaultData.bookmarks.length; i++) {

				var item = defaultData.bookmarks[i];
				var date = undefined;
				if (item.date) {
					date = Date.parse(item.date);
				}
				var bookmark = new UrlReference(item.url, item.title, date);

				bookmark.defaultEntry = true;
				bookmark.iconFile32 = item.iconFile32 ? item.iconFile32 : bookmark.iconFile32;
				bookmark.iconFile64 = item.iconFile64 ? item.iconFile64 : bookmark.iconFile64;
				bookmark.thumbnailFile = item.thumbnailFile ? item.thumbnailFile : bookmark.thumbnailFile;
				bookmark.visitCount = item.visitCount ? item.visitCount : bookmark.visitCount;
				bookmark.lastVisited = item.lastVisited ? item.lastVisited : bookmark.lastVisited;

				folder.addItem(bookmark);
			}
			this.bookmarkStore.write(folder, function() {
				window.close();
			}, function(e, msg) {
				Mojo.Log.error("Failure adding default bookmark: %s, msg: '%s'", e, msg);
				window.close();
			});
		}
	}
	catch (e) {
		Mojo.Log.logException(e, "_addDefaultBookmarks");
		window.close();
	}

	delete this.bookmarkStore;
};

AppAssistant.prototype._processDefaultData = function(defaultData) {

	try {
		var onSuccess = this._addDefaultBookmarks.bind(this, defaultData);
		if (defaultData && defaultData.append) {

			this.bookmarkStore = new BookmarkStore(
				{database: this.getDatabase()},
				onSuccess,
				function(msg, e) {
					Mojo.Log.error("Failed to create the bookmark store %s.", msg);
					window.close();					
				}.bind(this));
		} else {

			// Default was always to delete all previous bookmarks and then add
			// the given set of bookmarks to the DB. We keep this the default.
			this.bookmarkStore = new BookmarkStore(
				{database: this.getDatabase()},
				function() {
					this.bookmarkStore.deleteDefaultBookmarks(
						onSuccess,
						function(msg, e) {
							Mojo.Log.error('Failure deleting default bookmarks: %s.', msg);
							delete this.bookmarkStore;
							window.close();
						}.bind(this));
				}.bind(this),
				function(msg, e) {
					Mojo.Log.error("Failed to create the bookmark store %s.", msg);
					window.close();
				}.bind(this));
		}
	} 
	catch(e) {
		Mojo.Log.logException(e, "_processDefaultData");
		window.close();
	}
};

WebPreferences = Class.create({
	
	kCookieName: "WebPreferencesCookie",

	_fields: {
		'ClearCache': false, 
		'ClearCookies': false,
		'ClearHistory': false,
		'EnableJavaScript': true, 
		'AcceptCookies': true,
		'BlockPopups': true
	},
	
	initialize: function() {
			
		try {
			var cookie = new Mojo.Model.Cookie(this.kCookieName);
			var preferences = cookie.get() || {};
			
			// Setup the properties  
			for (var field in this._fields) {
				
				if (this._fields.hasOwnProperty(field)) {
					this[field] = this._fields[field];
					if (typeof preferences[field] !== 'undefined') {
						this[field] = preferences[field];
					}
				}
			}
		}
		catch (e) {
			// if something gets wonky in the cookies database and we throw an exception
			// then the framework stops loading and things go really wrong.
			Mojo.Log.logException(e);
		}
	},

	activate: function(actor) {
		
		try {
			if (actor) {
				if (actor.clearCache && this.ClearCache) {
					//Mojo.Log.info("@@@ WEB PREFS: Clearing Cache");
					actor.clearCache();
					this.ClearCache = false;
				}
				
				if (actor.clearCookies && this.ClearCookies) {
					//Mojo.Log.info("@@@ WEB PREFS: Clearing Cookies");
					actor.clearCookies();
					this.ClearCookies = false;
				}
				
				if (actor.clearHistory && this.ClearHistory) {
					//Mojo.Log.info("@@@ WEB PREFS: Clearing History");
					actor.clearHistory();
					this.ClearHistory = false;
				}
				
				if (actor.setBlockPopups) {
					//Mojo.Log.info("@@@ WEB PREFS: BlockPopups=", this.BlockPopups);
					actor.setBlockPopups(this.BlockPopups);
				}
				
				if (actor.setEnableJavaScript) {
					//Mojo.Log.info("@@@ WEB PREFS: EnableJavaScipt=", this.EnableJavaScript);
					actor.setEnableJavaScript(this.EnableJavaScript);
				}
				
				if (actor.setAcceptCookies) {
					//Mojo.Log.info("@@@ WEB PREFS: AcceptCookies=", this.AcceptCookies);
					actor.setAcceptCookies(this.AcceptCookies);
				}
				
				// Store the new settings.
				this.save(); 
			}
		} catch (e) {
			
			Mojo.Log.logException(e, "Failed to update web preferences");
		}
	},
	
	save: function() {
		
		// Store the current settings.
		var cookie = new Mojo.Model.Cookie(this.kCookieName);
		var preferences = {};
		
		for (var field in this._fields) {
			if (this._fields.hasOwnProperty(field)) {
				preferences[field] = this[field];
			}
		}
		
		cookie.put(preferences);
	}
});

AppAssistant.WebPreferences = new WebPreferences();
