/**
 * @name preferences-assistant.js
 * @fileOverview The assistant for the Preferences scene. Controls application level
 * settings.
 *
 * Copyright 2008-2009 Palm, Inc. All rights reserved.
 */

/**
 * Constructor.
 * @param {PageAssistant} pageAssistant
 */
function PreferencesAssistant(webPreferences) {
	this._webPreferences = webPreferences;
	this._historyStore = new HistoryStore({
		database: Mojo.Controller.appController.assistant.getDatabase()
	});	

	// Setup the event handlers.
	this._searchEngineChangeHandler = this._searchEngineChange.bindAsEventListener(this);
	this._clearHistoryHandler = this.clearHistory.bindAsEventListener(this);
	this._clearCacheHandler = this.clearCache.bindAsEventListener(this);
	this._clearCookiesHandler = this.clearCookies.bindAsEventListener(this);

	this._onCardActivateHandler = this._onCardActivate.bind(this);
	this._onCardDeactivateHandler = this._onCardDeactivate.bind(this);
}

PreferencesAssistant.DefaultSearchProvider = {

	id: 'google',
	title: $L('Google'),
	weburl: $L('http://www.google.com/m/search?client=ms-palm-webOS&channel=bm&q=#{query}')
};

PreferencesAssistant.prototype.setup = function() {
	
	try {
		this.setupPopupsWidget();
		this.setupAcceptsCookiesWidget();
		this.setupJavaScriptWidget();
		this.setupSearchEngineWidget();
	} 
	catch (e) {
		Mojo.Log.logException(e, 'PreferencesAssistant#setup');
	}
};

PreferencesAssistant.prototype.cleanup = function() {

	// Cancel outstanding service requests
	this._serviceListRequest.cancel();
	this._serviceDefaultRequest.cancel();

	// Store the current settings for next launch.
	this._webPreferences.save();	
};

PreferencesAssistant.prototype.activate = function() {
			
	this.controller.listen('clear_history_button', Mojo.Event.tap, this._clearHistoryHandler);
	this.controller.listen('clear_cache_button', Mojo.Event.tap, this._clearCacheHandler);
	this.controller.listen('clear_cookies_button', Mojo.Event.tap, this._clearCookiesHandler);
	this.controller.listen('search-selector', 'mojo-property-change', this._searchEngineChangeHandler);

	// Add card focus handlers.
	this.controller.document.addEventListener(Mojo.Event.activate, this._onCardActivateHandler, false);
	this.controller.document.addEventListener(Mojo.Event.deactivate, this._onCardDeactivateHandler, false);
	
	// Reload the preferences
	this.controller.modelChanged(this._webPreferences);
};

PreferencesAssistant.prototype.deactivate = function() {

	this.controller.stopListening('clear_history_button', Mojo.Event.tap, this._clearHistoryHandler); 
	this.controller.stopListening('clear_cache_button', Mojo.Event.tap, this._clearCacheHandler);
	this.controller.stopListening('clear_cookies_button', Mojo.Event.tap, this._clearCookiesHandler);
	this.controller.stopListening('search-selector', 'mojo-property-change', this._searchEngineChangeHandler);

	// Cleanup focus handlers.
	this.controller.document.removeEventListener(Mojo.Event.activate, this._onCardActivateHandler, false);
	this.controller.document.removeEventListener(Mojo.Event.deactivate, this._onCardDeactivateHandler, false);
};

PreferencesAssistant.prototype._onCardActivate = function(){

	// Reload the preferences
	this.controller.modelChanged(this._webPreferences);
};

PreferencesAssistant.prototype._onCardDeactivate = function(){
};

PreferencesAssistant.prototype.clearHistory = function(event) {
	this.controller.showAlertDialog({
		onChoose: function(value) {
			if (value === 'ok') {
				this._webPreferences.ClearHistory = true;
				
				// We also now clear the local history list.
				this._historyStore.deleteHistoryBefore(new Date(),
					function(){},
					function(msg, e) {
						Mojo.Log.error("History delete failed: %s", msg);
					});
			}
		}.bind(this),
		title:$L('Clear history'),
		message:$L('Your browsing history will be permanently deleted.'),
		cancelable:true,
		choices:[
			{label:$L('Clear history'), value:'ok'},
			{label:$L('Cancel'), value:'cancel'}
		]
	});
};

PreferencesAssistant.prototype.clearCache = function(event) {
	this.controller.showAlertDialog({
		onChoose: function(value) {
			try {
				if (value === 'ok') {
					this._webPreferences.ClearCache = true;
				}
			}
			catch (e) {
				Mojo.Log.logException(e, "clearing cache");
			}
		}.bind(this),
		title:$L('Clear cache'),
		message:$L('Clear your browser cache?'),
		cancelable:true,
		choices:[
		{label:$L('Clear cache'), value:'ok', type:'color'},
		{label:$L('Cancel'), value:'cancel'}
		    ]
	});
};

PreferencesAssistant.prototype.clearCookies = function(event) {
	this.controller.showAlertDialog({
		onChoose: function(value) {
			try {
				if (value === 'ok') {
					this._webPreferences.ClearCookies = true;
				}
			}
			catch (e) {
				Mojo.Log.logException(e, "clearing cookies");
			}
		}.bind(this),
		title:$L('Clear cookies'),
		message:$L('Clear your browser cookies?'),
		cancelable:true,
		choices:[
		{label:$L('Clear cookies'), value:'ok', type:'color'},
		{label:$L('Cancel'), value:'cancel'}
		    ]
	});
};


/**
 * Called when the user selects a search engine
 */
PreferencesAssistant.prototype._searchEngineChange = function(event) {

	var choice = [event.value];
	this.controller.serviceRequest("palm://com.palm.systemservice", {
		
		method: 'setPreferences',
		parameters: {
			'defaultWebSearch': choice
		}
	});
};

/**
 * A setup helper to query search defaults and notify on system changes
 */
PreferencesAssistant.prototype.setupSearchEngineWidget = function() {

	this._searchEngineModel = {};
	this._searchEngineChoices = [];

	var attributes = {
		choices: this._searchEngineChoices,
		modelProperty: 'currentEngine'
	};

	var searchDefaultResponse = function(status, response) {

		this._searchEngineModel.currentEngine = undefined;
		// Assume a default choice and if we have a success then populate with a the real choice
		if (status && response && response.defaultWebSearch && response.defaultWebSearch.length !== 0) {
			this._searchEngineModel.currentEngine = response.defaultWebSearch[0];

		} 

		this.controller.modelChanged(this._searchEngineModel);		
	};

	var searchListResponse = function(status, response) {
		
		// We refresh the current set of choices so clear the old values.
		this._searchEngineChoices.splice(0);

		// Assume a default search list and if we have a success then populate with the real deal.
		var searchEngines = [];
		if (status && response && response.webSearchList && response.webSearchList[Mojo.Locale.current]) {
			searchEngines = response.webSearchList[Mojo.Locale.current];
		} else {
			searchEngines.push(PreferencesAssistant.DefaultSearchProvider);
		}

		searchEngines.each(function(engine) {

			var choice = {};
			choice.label = engine.title;
			choice.value = engine.id;
			this._searchEngineChoices.push(choice);

		}.bind(this));
	};

	this.controller.setupWidget('search-selector', attributes, this._searchEngineModel);

	// Query the system service for the current set of search options.
	this._serviceListRequest = this.controller.serviceRequest("palm://com.palm.systemservice", {
		method: 'getPreferences',
		parameters: {
			'subscribe': true,
			'keys': ['webSearchList']
		},
		onSuccess: searchListResponse.bind(this, true),
		onFailure: searchListResponse.bind(this, false)
	});

	this._serviceDefaultRequest = this.controller.serviceRequest("palm://com.palm.systemservice", {
		method: 'getPreferences',
		parameters: {
			'subscribe': true,
			'keys': ['defaultWebSearch']
		},
		onSuccess: searchDefaultResponse.bind(this, true),
		onFailure: searchDefaultResponse.bind(this, false)
	});

};

PreferencesAssistant.prototype.setupAcceptsCookiesWidget = function(event) {

	// This is supposed to be a tri-state setting, but WebKit only supports true/false
	// at present.
	var attributesModel = [
		{label:$L('Yes'), value:true},
		{label:$L('No'), value:false} ];

	var attributes = {
		modelProperty: "AcceptCookies",
		trueValue: true,
		trueLabel: $L('Yes'),
		falseValue: false,
		falseLabel: $L('No')
	};
	
	this.controller.setupWidget('acceptCookies', attributes, this._webPreferences);
};

PreferencesAssistant.prototype.setupPopupsWidget = function(event) {

	var attributes = {
		modelProperty: "BlockPopups",
		trueValue: true,
		trueLabel: $L('Yes'),
		falseValue: false,
		falseLabel: $L('No')
	};
	
	this.controller.setupWidget('blockPopups', attributes, this._webPreferences);
};

PreferencesAssistant.prototype.setupJavaScriptWidget = function(event) {

	var attributes = {
		modelProperty: "EnableJavaScript",
		trueValue: true,
		trueLabel: $L('On'),
		falseValue: false,
		falseLabel: $L('Off')
	};
	
	this.controller.setupWidget('javascriptEnabled', attributes, this._webPreferences);
};

/**
 * handle a menu command.
 */
PreferencesAssistant.prototype.handleCommand = function(event) {
	
	try {
		switch (event.type) {
		
		case Mojo.Event.command:
			
			if (event.command === Mojo.Menu.helpCmd) { 
				this._showHelpCommand();
			}
			break;
			
		case Mojo.Event.commandEnable:
			
			// Standard Application Menu commands.
			if (event.command === Mojo.Menu.helpCmd) {
				
				event.stopPropagation(); // Enable the chosen menuitems
				
			} 				
			break;
		}
	} 
	catch (e) {
		Mojo.Log.logException(e, 'handleCommand');
	}
};

PreferencesAssistant.prototype._showHelpCommand = function() {
	
	// Launch the help system.
	AppAssistant.launchHelp();
};
