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

const EXPORTED_SYMBOLS = ['Version'];

const Cc = Components.classes;
const Ci = Components.interfaces;
const module = Components.utils.import;

const ID = '{DDC359D1-844A-42a7-9AA1-88A850A938A8}';

const runtime = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULAppInfo).QueryInterface(Ci.nsIXULRuntime);
const comparator = Cc["@mozilla.org/xpcom/version-comparator;1"].getService(Ci.nsIVersionComparator);

let _callbacks = [];

const Version = {
		TOPIC_SHOWABOUT: "DTA:showAbout",
		ID: ID,
		LOCALE: Cc["@mozilla.org/chrome/chrome-registry;1"].getService(Ci.nsIXULChromeRegistry).getSelectedLocale('global'),
		APP_NAME: runtime.name.toLowerCase().replace(/ /, ''),
		OS: runtime.OS.toLowerCase(),
		APP_VERSION: runtime.version,
		APP_ID: runtime.ID,
		VERSION: '0.0',
		BASE_VERSION: '0.0',
		NAME: 'DownThemAll!',
		moz1: false,
		moz2: false,
		ready: false,
		showAbout: null,
		compareVersion: function(version, cmp) {
			if (!cmp) {
				[version, cmp] = [this.VERSION, version];
			}
			return comparator.compare(version, cmp);
		},
		getInfo: function(callback) {
			if (this.ready) {
				callback.call(callback, this);
			}
			else {
				_callbacks.push(callback);
			}
		}
};

function completeVersion(addon) {
	if (addon) {
		Version.VERSION = addon.version;
		Version.BASE_VERSION = Version.VERSION.replace(/^([\d\w]+\.[\d\w]+).*?$/, '$1');
		Version.NAME = addon.name;
		Version.ready = true;
	}
	
	_callbacks.forEach(function(c) c.call(c, Version));
	_callbacks = [];
}

/**
 * Compares two version literals according to mozilla rules
 * @param version (string) Optional. Version.  If not given extension version will be used.
 * @param cmp (string) Version to compare to.
 * @return nsIVersionComparator result
 */

try {
	// moz-1.9.3+
	module("resource://gre/modules/AddonManager.jsm");
	Version.moz2 = true;
	AddonManager.getAddonByID(Version.ID, function(addon) {
		completeVersion(addon);
	});
}
catch (ex) {
	// moz-1.9.2-
	Version.moz1 = true;
	const ITEM = Cc["@mozilla.org/extensions/manager;1"].getService(Ci.nsIExtensionManager).getItemForID(ID);
	completeVersion(ITEM);
}