var EXPORTED_SYMBOLS = [ 'UW_util' ];

const UW_SERVICE = Components
    .classes["@unity_webapps.mozdev.org/unity_webapps-service;1"]
    .getService(Components.interfaces.uwIGreasemonkeyService)
    .wrappedJSObject;

const ioService = Components.classes["@mozilla.org/network/io-service;1"]
    .getService(Components.interfaces.nsIIOService);

var UW_util = {
    getService: function() {
	return UW_SERVICE;
    },

    logError: function(e) {
	dump(e + '\n');
    },

    isGreasemonkeyable: function(url) {
	var scheme = ioService.extractScheme(url);

	switch (scheme) {
	case "http":
	case "https":
	case "ftp":
	case "data":
	case "file":
	    return true;
	}

	return false;
    },

    windowId: function(win) {
	try {
	    // Do not operate on chrome windows.
	    win.QueryInterface(Components.interfaces.nsIDOMChromeWindow);
	    return null;
	} catch (e) {
	    // We want this to fail.  Catch is no-op.
	}

	try {
	    // Dunno why this is necessary, but sometimes we get non-chrome windows
	    // whose locations we cannot access.
	    var href = win.location.href;
	    if (!UW_util.isGreasemonkeyable(href)) return null;
	} catch (e) {
	    return null;
	}

	var domWindowUtils = win
	    .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
	    .getInterface(Components.interfaces.nsIDOMWindowUtils);
	var windowId;
	try {
	    windowId = domWindowUtils.currentInnerWindowID;
	} catch (e) { }
	if ('undefined' == typeof windowId) {
	    // Firefox <4.0 does not provide this, use the document instead.
	    // (Document is a property of the window, and should let us dig into the
	    // "inner window" rather than always getting the same "outer window", due
	    // to bfcache.  https://developer.mozilla.org/en/Inner_and_outer_windows )
	    return win.document;
	}
	return windowId;
    },

    windowIdForEvent: function(aEvent) {
	var doc = aEvent.originalTarget;
	try {
	    doc.QueryInterface(Components.interfaces.nsIDOMHTMLDocument);
	} catch (e) {
	    return null;
	}

	return UW_util.windowId(doc.defaultView);
    }
};
