// -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*-

var Cu = Components.utils;
var Ci = Components.interfaces;
var Cc = Components.classes;
var Cr = Components.results;
var Cm = Components.manager;

Cu.import("resource://gre/modules/Services.jsm");

var resource = Services.io.getProtocolHandler("resource").QueryInterface(Ci.nsIResProtocolHandler);
var styleSheetService = Cc["@mozilla.org/content/style-sheet-service;1"].getService(Components.interfaces.nsIStyleSheetService);
var ios = Cc["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
var wm = Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator);

var observer = null;
var consoleService = Cc["@mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService);

var windowListener = {
    onOpenWindow: function(aWindow) {
        if (!(aWindow.chromeFlags & Ci.nsIWebBrowserChrome.CHROME_PERSONAL_TOOLBAR)) {
            let domWindow = aWindow.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
            domWindow.addEventListener("load", function() {
                domWindow.removeEventListener("load", arguments.callee, false);

                new UnityPrefs(domWindow);
            }, false);
        }
    },

    onCloseWindow: function(aWindow) {},
    onWindowTitleChange: function(aWindow, aTitle) {}
};

function startup(params, reason) {
try {
    Cm.addBootstrappedManifestLocation(params.installPath);

    var uri = ios.newURI("chrome://unity/skin/browser.css", null, null);
    styleSheetService.loadAndRegisterSheet(uri, styleSheetService.USER_SHEET);

    var path = params.installPath.clone();
    path.append('content');
    let alias = Services.io.newFileURI(path);

    resource.setSubstitution("unity", alias);

    Cu.import("resource://unity/observer.js");

    observer = new Observer();
    observer.activate();

    Cu.import("resource://unity/prefs.js");

    wm.addListener(windowListener);
} catch (x) {dump(x);}
}

function shutdown(params, reason) {
    wm.removeListener(windowListener);

    Cu.unload("resource://unity/prefs.js");

    observer.deactivate();
    observer = null;

    Cu.unload("resource://unity/observer.js");

    resource.setSubstitution("unity", null);

    var uri = ios.newURI("chrome://unity/skin/browser.css", null, null);
    styleSheetService.unregisterSheet(uri, sss.USER_SHEET);
    Cm.removeBootstrappedManifestLocation(params.installPath);
}
