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

const EXPORTED_SYMBOLS = [
	'available',
	'show'
];

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

let Preferences = {};
module("resource://dta/preferences.jsm", Preferences);

let available = false;
let service = null;
let alerting = false;

const Observer = {
	_func: null,
	observe: function(aSubject, aTopic, aData) {
		switch (aTopic) {
		case "alertfinished":
			alerting = false;
			break;
		case "alertclickcallback":
			if (this._func) {
				try {
					this._func();
				}
				catch (ex) {
					Cu.reportError(ex);
					// no op
				}
			}
			this._func = null;
			break;
		}
	}
};

try {
	service = Cc['@mozilla.org/alerts-service;1'].getService(Ci.nsIAlertsService);
	Preferences.makeObserver(Observer);
	available = true;
}
catch (ex) {
	// no-op
}

function show(title, msg, callback) {
	if (!available) {
		throw new Exception("Alerting Service not available on this platform!");
	}
	if (alerting) {
		return;
	}
	alerting = true;

	let clickable = false;
	Observer._func = null;
	if (typeof callback == 'function') {
		clickable = true;
		Observer._func = callback;
	}
	service.showAlertNotification(
		"chrome://dta/skin/common/alert.png",
		title,
		msg,
		clickable,
		null,
		Observer
		);
}