/*
 * LICENCE[[
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1/CeCILL 2.O
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is utc.fr code.
 *
 * The Initial Developer of the Original Code is
 * sylvain.spinelli@kelis.fr on behalf of UTC
 *
 * Portions created by the Initial Developer are Copyright (C) 2005
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * or the CeCILL Licence Version 2.0 (http://www.cecill.info/licences.en.html),
 * in which case the provisions of the GPL, the LGPL or the CeCILL are applicable
 * instead of those above. If you wish to allow use of your version of this file
 * only under the terms of either the GPL, the LGPL or the CeCILL, and not to allow
 * others to use your version of this file under the terms of the MPL, indicate
 * your decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL, the LGPL or the CeCILL. If you do not
 * delete the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL, the LGPL or the CeCILL.
 * ]]LICENCE
 */

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 nsIPrefBranch            = Components.interfaces.nsIPrefBranch;
const nsISupportsString        = Components.interfaces.nsISupportsString;
const nsIWindowWatcher         = Components.interfaces.nsIWindowWatcher;
const nsIDOMWindow			   = Components.interfaces.nsIDOMWindow;

/**
 * Parametres de lancement traites ici :
 *			installWsppack 			path vers le wspPack
 *			installXpi 				path vers le xpi
 *			installJar 				path vers le jar
 *			createWsp.code 			code de l'atelier a creer (lie a createWsp.wspmeta)
 *			createWsp.wspmeta 		path vers le .wspmeta (lie a createWsp.code) 
 */

var scClh = {

  /* 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(pCmdLine) {
	if (pCmdLine.preventDefault) return;
	
	var vInfo 			= Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULAppInfo);
	var vIsFfXpi = vInfo.ID == "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}";
	
	pCmdLine.preventDefault = !vIsFfXpi; // si on est sur xulrunner, les clh s'arretent là
	
	var vPrefs = Components.classes["@mozilla.org/preferences-service;1"].getService(nsIPrefBranch);
	var vConsoleService = Components.classes["@mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService);
	
	try {
		
		var vWinWatch = Components.classes["@mozilla.org/embedcomp/window-watcher;1"].getService(nsIWindowWatcher);
		var vEnum = vWinWatch.getWindowEnumerator(null);
		
			
		if(!vIsFfXpi){ // si on n'est pas sur FFx
			// traitement des installeurs
			var vIsInstallPack = pCmdLine.findFlag("installWsppack", true)>-1 | pCmdLine.findFlag("installXpi", true)>-1 | pCmdLine.findFlag("installJar", true)>-1;
			var vIsCreateWspParam = pCmdLine.findFlag("createWsp.code", true)>-1 && pCmdLine.findFlag("createWsp.wspmeta", true)>-1;
			var vIsDeclareSrvParam = pCmdLine.findFlag("declareSrv.url", true)>-1;
			
			if(vIsInstallPack){
				var vAppStartup = Components.interfaces.nsIAppStartup;
				var vInstallWin = vWinWatch.openWindow(null, "chrome://scenaricms/content/installmgr/installmgrAutoMode.xul", "_blank", "chrome,centerscreen,dialog=no", pCmdLine);
	       		return;
			}
			
			if(vIsDeclareSrvParam){
				// A REVOIR : passer en fenetre no modale et sortir du CLH.
				var vDeclareSrv = vWinWatch.openWindow(null, "chrome://scenaricms/content/wspmgr/srvdeclare/declareSilentMode.xul", "_blank", "chrome,centerscreen,dialog=no,all,modal=yes", pCmdLine);
				// On ferme toutes les fenetres actives de l'application
				while (vEnum.hasMoreElements()){
					var vDomWindow = vEnum.getNext().QueryInterface(nsIDOMWindow);
					try{vDomWindow.close();} catch (e) {}
				}
				return;
			}
			
			if(vIsCreateWspParam){
				// A REVOIR : passer en fenetre no modale et sortir du CLH.
				var vCreateWsp = vWinWatch.openWindow(null, "chrome://scenaricms/content/wspmgr/create/createSilentMode.xul", "_blank", "chrome,centerscreen,dialog=no,all,modal=yes", pCmdLine);
				// On ferme toutes les fenetres actives de l'application
				while (vEnum.hasMoreElements()){
					var vDomWindow = vEnum.getNext().QueryInterface(nsIDOMWindow);
					try{vDomWindow.close();} catch (e) {}
				}
				return;
			}
			
			//demarrage normal
			if(!vEnum.hasMoreElements()){// si SC pas déja lancé, on le lance
				var chromeURI = vPrefs.getCharPref("toolkit.defaultChromeURI");
				var vNewWin = vWinWatch.openWindow(null, chromeURI, "_blank", "chrome,dialog=no", pCmdLine);
			}else{// si SC est déja lancé, on donne le focus à la fenêtre
				var vDomWindow = vEnum.getNext().QueryInterface(nsIDOMWindow);
				try{vDomWindow.focus();} catch (e) {}
			}
		}else{// on est sur FFx (xpi)
			
		}
	} catch (e) {
		vConsoleService.logStringMessage("init Failed : "+e);
	}
	
  },

  helpInfo : "SCENARI",

  /* nsIFactory */
  createInstance : function mdh_CI(outer, iid) {
    if (outer != null) throw Components.results.NS_ERROR_NO_AGGREGATION;
    return this.QueryInterface(iid);
  },
  
  lockFactory : function mdh_lock(lock) {
    /* no-op */
  }
};

const clh_contractID = "@scenari/scenari-clh;1";
const clh_CID = Components.ID("{3CAE0595-E91E-402C-8936-4B886A7DE3FE}");

var Module = {
  /* 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 scClh.QueryInterface(iid);
    throw components.results.NS_ERROR_FAILURE;
  },

  registerSelf : function mod_regself(compMgr, fileSpec, location, type) {
    var compReg = compMgr.QueryInterface(nsIComponentRegistrar);
    compReg.registerFactoryLocation(clh_CID,
                                    "scClh",
                                    clh_contractID,
                                    fileSpec,
                                    location,
                                    type);
    var catMan = Components.classes["@mozilla.org/categorymanager;1"].getService(nsICategoryManager);
    catMan.addCategoryEntry("command-line-handler",  "n-scenari", 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", "n-scenari");
  },

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

function NSGetModule(compMgr, fileSpec) {
  return Module;
}

//fcts utiles
function debug(pText){
	var vConsoleService = Components.classes["@mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService);
	vConsoleService.logStringMessage(pText);
}

function listProperties(pObj){
	var vRes = "";
	var vProp = null;
	for (vProp in pObj) {
		try {
			vRes += vProp +'(' + pObj[vProp]+ ')'+ "\n";
		} catch(e){
			vRes += vProp +' -> toString in error\n';
		}
	}
	return vRes;
}
