/* http://developer.mozilla.org/en/docs/Chrome:_Command_Line */

//const nsIAppShellService    = Components.interfaces.nsIAppShellService;
const nsISupports           = Components.interfaces.nsISupports;
const nsICategoryManager    = Components.interfaces.nsICategoryManager;
const nsIComponentRegistrar = Components.interfaces.nsIComponentRegistrar;
const nsICommandLine        = Components.interfaces.nsICommandLine;
const nsICommandLineHandler = Components.interfaces.nsICommandLineHandler;
const nsIFactory            = Components.interfaces.nsIFactory;
const nsIModule             = Components.interfaces.nsIModule;
//const nsIWindowWatcher      = Components.interfaces.nsIWindowWatcher;

/**
 * The XPCOM component that implements nsICommandLineHandler.
 * It also implements nsIFactory to serve as its own singleton factory.
 */
const myEMHandler = {

  /* nsISupports */
  QueryInterface : function clh_QI(iid) {
    if (iid.equals(nsICommandLineHandler) ||
        iid.equals(nsIFactory) ||
        iid.equals(nsISupports))
      return this;

    throw Components.results.NS_ERROR_NO_INTERFACE;
  },

  /* nsICommandLineHandler */
  handle : function clh_handle(cmdLine) {

    try {
      var currentArg, prefs
      var argCount = cmdLine.length;
      var bRefocusWindow = true;

      for (var i = 0; i < argCount; ++i) {
        currentArg = cmdLine.getArgument(i);
        // var mConsoleService = Components.classes["@mozilla.org/consoleservice;1"]
               // .getService(Components.interfaces.nsIConsoleService)
        // mConsoleService.logStringMessage("cmdline " + i + " :\n" + currentArg);

        if (/\.emx$|\.emx\?*/i.test(currentArg)) {
          bRefocusWindow = false;

          if (/^emusic\:\/\/|^https?\:\/\//i.test(currentArg)) {
            currentArg = currentArg.replace(/^emusic:\/\//, "http://");
          } else {
            currentArg = cmdLine.resolveFile(currentArg).path;
          }

          prefs = Components.classes["@mozilla.org/preferences-service;1"]
                    .getService(Components.interfaces.nsIPrefService)
                    .getBranch("eMusic.");

          prefs.setCharPref("cmdLineValue", currentArg);

          var downloadDeck = prefs.getIntPref("downloadDeck")
          prefs.setIntPref("currentDeck", downloadDeck);

        }
      }

      var windowMediator = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                                     .getService(Components.interfaces.nsIWindowMediator);
      var win = windowMediator.getMostRecentWindow("emusic:window");
      if (win) {
        if (bRefocusWindow) {
          win.focus();
        }
        cmdLine.preventDefault = true;
        return;
      }
    } catch (e) {
      Components.utils.reportError(e);
      return true;
    }
    return true;
  },

  helpInfo : "  just the emp path please\n",

  /* nsIFactory */

  createInstance : function clh_CI(outer, iid) {
    if (outer != null)
      throw Components.results.NS_ERROR_NO_AGGREGATION;

    return this.QueryInterface(iid);
  },

  lockFactory : function clh_lock(lock) {
    /* no-op */
  }
};

// CHANGEME: change the contract id, CID, and category to be unique
// to your application.
//const clh_contractID = "@mozilla.org/commandlinehandler/general-startup;1?type=emhandler";
const clh_contractID = "@mozilla.org/toolkit/default-clh;1?type=emhandler";
const clh_CID = Components.ID("{EA8CD2F1-920F-48b1-8C5E-84BB23139C73}");

// category names are sorted alphabetically. Typical command-line handlers use a
// category that begins with the letter "m".
const clh_category = "m-emhandler";

/**
 * The XPCOM glue that implements nsIModule
 */
const myEMHandlerModule = {
  /* nsISupports */
  QueryInterface : function mod_QI(iid) {
    if (iid.equals(nsIModule) ||
        iid.equals(nsISupports))
      return this;

    throw Components.results.NS_ERROR_NO_INTERFACE;
  },

  /* nsIModule */
  getClassObject : function mod_gch(compMgr, cid, iid) {
    if (cid.equals(clh_CID))
      return myEMHandler.QueryInterface(iid);

    throw Components.results.NS_ERROR_NOT_REGISTERED;
  },

  registerSelf : function mod_regself(compMgr, fileSpec, location, type) {
    var compReg = compMgr.QueryInterface(nsIComponentRegistrar);
    compReg.registerFactoryLocation(clh_CID,
                                    "myEMHandler",
                                    clh_contractID,
                                    fileSpec,
                                    location,
                                    type);

    var catMan = Components.classes["@mozilla.org/categorymanager;1"].
      getService(nsICategoryManager);
    catMan.addCategoryEntry("command-line-handler",
                            clh_category,
                            clh_contractID, true, true);
  },

  unregisterSelf : function mod_unreg(compMgr, location, type) {
    var compReg = compMgr.QueryInterface(nsIComponentRegistrar);
    compReg.unregisterFactoryLocation(clh_CID, location);

    var catMan = Components.classes["@mozilla.org/categorymanager;1"].
      getService(nsICategoryManager);
    catMan.deleteCategoryEntry("command-line-handler", clh_category);
  },

  canUnload : function (compMgr) {
    return true;
  }
};

/* The NSGetModule function is the magic entry point that XPCOM uses to find what XPCOM objects
 * this component provides
 */
function NSGetModule(comMgr, fileSpec) {
  return myEMHandlerModule;
}