/*
 * 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 kelis.fr code.
 *
 * The Initial Developer of the Original Code is
 * antoine.pourchezi@kelis.fr
 *
 * Portions created by the Initial Developer are Copyright (C) 2006
 * 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;

const prefLastVersionRun	   = "scenari.app.lastVersionRun"; 

/**
  * Permet de lancer la cr�ation d'atelier(s) et �ventuellement la copie de donn�es
 */

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;
	pCmdLine.preventDefault = false;//on continue le d�marrage normal
	
	var vPrefs = Components.classes["@mozilla.org/preferences-service;1"].getService(nsIPrefBranch);
	var vConsoleService = Components.classes["@mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService);
	var vWinWatch = Components.classes["@mozilla.org/embedcomp/window-watcher;1"].getService(nsIWindowWatcher);
	var vInfo = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULAppInfo);
	
	try {
		var chromeURI = vPrefs.getCharPref("toolkit.defaultChromeURI");
		if(vPrefs.getPrefType(prefLastVersionRun)!=32 || (vPrefs.getPrefType(prefLastVersionRun)==32 && vPrefs.getCharPref(prefLastVersionRun)!=vInfo.version)){
			//vWspObj = null;//wsp.code, wsp.wspmetaPath, wsp.dataPath
			
						var vSrvList = [];		

			
			/* wrapper de commanLine */
			function scCmdLine(vObj) {
				this.argList = vObj;
			}
			scCmdLine.prototype = {
				 /** nsICommandLine **/
					 
				 findFlag : function(flag, caseSensitive){
				 	if(flag=='declareSrv.url' || flag=='declareSrv.wspCode' || flag=='declareSrv.title' || flag=='declareSrv.login' || flag=='declareSrv.password'){
						return 0;
					}else{
						return -1;
					}
				},
				 handleFlagWithParam : function(flag, caseSensitive){
					switch(flag) {
						case "declareSrv.url"    	: return this.argList.url;
						case "declareSrv.title" 	: return this.argList.title;
						case "declareSrv.login" 	: return this.argList.login!="" ? this.argList.login : null;
						case "declareSrv.password" 	: return this.argList.password!="" ? this.argList.password : null;
						case "declareSrv.wspCode" 	: return this.argList.wsps!="" ? this.argList.wsps : null;
						default : return null
					}
				},					
							
			     QueryInterface : function(pIId) {
			        if (!pIId.equals(Components.interfaces.nsISupports) &&
			            !pIId.equals(Components.interfaces.nsICommandLine)
			   			)throw Components.results.NS_ERROR_NO_INTERFACE;
					//this.fCh.QueryInterface(pIId);
			        return this;
			    }
			}
			
			for(var ii=0; ii<vSrvList.length; ii++){
				var vDeclareSrv = vWinWatch.openWindow(null, "chrome://scenaricms/content/wspmgr/srvdeclare/declareSilentMode.xul", "_blank", "chrome,centerscreen,modal", new scCmdLine(vSrvList[ii]));
			}
		
		}
	} catch (e) {
		vConsoleService.logStringMessage("init Failed : "+e);
	}
	
  },

  helpInfo : "SCENARIapp - WSPcreate",

  /* 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/scenariapp-srv-clh;1";
const clh_CID = Components.ID("{3CAE0595-E91E-402C-8936-5A886A7DE3FF}");

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",  "b-scenariapp-srv", 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", "b-scenariapp-srv");
  },

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

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

/** Utilitaires **/

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;
}
