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

const EXPORTED_SYMBOLS = ['getIcon'];

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://dta/api.jsm");
module("resource://dta/utils.jsm");

extendString(String);

setNewGetter(this, "FavIcons", function() {
	try {
		return Cc['@mozilla.org/browser/favicon-service;1']
	       .getService(Ci.nsIFaviconService);
	}
	catch (ex) {
		Debug.log("FavIcon Service not available", ex);
		return null;
	}
});

/**
 * Get the icon URI corresponding to an URI (special mac handling)
 * 
 * @author Nils
 * @author Stefano
 * @param link
 *          Some sort of DTA.URL, nsIURI or string to get the icon for
 * @param metalink
 *          Is it a metalink?
 * @param size
 *          The desired iconsize;
 * @return String containing the icon URI
 */
function getIcon(link, metalink, size) {
	if (metalink) {
		return "chrome://dta/skin/icons/metalink.png";
	}
	if (typeof(size) != 'number') {
		size = 16;
	}
	try {
		let url = link;
		if (link instanceof URL) {
			url = link.url;
		}
		else if (link instanceof Ci.nsIURI) {
			url = link.QueryInterface(Ci.nsIURL);
		}
		else if (link && link.url) {
			url = link.url;
		}
		if (typeof url == 'string' || url instanceof String) {
			try {
				url = url.toURL();
			}
			catch (ex) { /* no op */ }
		}
		if (url && url instanceof Ci.nsIURL) {
			if (FavIcons && /(?:\/|html?|aspx?|php\d?)$|\/[^.]*$/i.test(url.filePath)) {
				let icon = FavIcons.getFaviconImageForPage(url);
				if (icon.spec == FavIcons.defaultFavicon.spec) {
					let host = url.clone().QueryInterface(Ci.nsIURL);
					host.ref = host.query = host.filePath = "";
					icon = FavIcons.getFaviconImageForPage(host);
				}
				return icon.spec;
			}
			url = url.spec;
		}
		let ext = url.getExtension();
		return "moz-icon://file" + (ext ? '.' + ext : '') + "?size=" + size;
	}
	catch (ex) {
		Debug.log("updateIcon: failed to grab icon", ex);
	}
	return "moz-icon://foo.html?size=" + size;
};