/* You may find the license in the LICENSE file */

const EXPORTED_SYMBOLS = ['LoggedPrompter'];

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;
const Cu = Components.utils;
const module = Cu.import;
const Exception = Components.Exception;

module("resource://gre/modules/XPCOMUtils.jsm");
module("resource://dta/utils.jsm");

ServiceGetter(this, "WindowWatcherService", "@mozilla.org/embedcomp/window-watcher;1", "nsIWindowWatcher");

/**
 * Provides nsIPrompt/nsIAuthPrompt
 * The nsIPrompt implementation will log any alerts instead of actually displaying them
 * 
 * @param window Associated window (that will be the parent of any prompt dialogs)
 */
function LoggedPrompter(window) {
	/**
	 * Property providing nsIAuthPrompt
	 */
	setNewGetter(
		this,
		'authPrompter',
		function() {
			return WindowWatcherService
				.getNewAuthPrompter(window)
				.QueryInterface(Ci.nsIAuthPrompt);
		}
	);

	/**
	 * Property providing nsIPrompt
	 */
	setNewGetter(
		this,
		'prompter',
		function() {
			let _p = WindowWatcherService
				.getNewPrompter(window)
				.QueryInterface(Ci.nsIPrompt);

			// Log any alerts instead of showing a dialog.
			// Everything else pass thru to the actual prompter.
			let _dp = {
				QueryInterface: XPCOMUtils.generateQI([Ci.nsIPrompt]),
				alert: function(title, text) Debug.log(text, title),
				alertCheck: function(title, text, cm, cv) Debug.log(text, title),
				confirm: function(title, text) _p.confirm(title, text),
				confirmCheck: function(title, text, cm, cv) _p.confirmCheck(title, text, cm, cv),
				confirmEx: function(title, text, bflags, bt0, bt1, bt2, cm, cv) _p.confirmEx(title, text, bflags, bt0, bt1, bt2, cm, cv),
				prompt: function(title, text, value, cm, cv) _p.prompt(title, text, value, cm, cv),
				promptPassword: function(title, text, password, cm, cv) _p.promptPassword(title, text, password, cm, cv),
				promptUsernameAndPassword: function(title, text, un, pw, cm, cv) _p.promptUsernameAndPassword(title, text, un, pw, cm, cv),
				select: function(title, text, count, list, selection) _p.select(title, text, count, list, selection)
			}
			return _dp;
		}
	);	
}