/*
 * 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 
 * sylvain.spinelli@kelis.fr 
 * 
 * Portions created by the Initial Developer are Copyright (C) 2008
 * 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 or the LGPL, 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 or the LGPL. 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 nsIConsoleService = Components.interfaces.nsIConsoleService;
const nsISupports = Components.interfaces.nsISupports;

const SHAREDRES_CONTRACTID = '@scenari.com/sharedres;1';
const SHAREDRES_CID = Components.ID('{64896643-3859-4BDA-897E-5718725CE2A2}');
const SHAREDRES_IID = Components.interfaces.scISharedRes;


/*  */
function scSharedRes() {
}

/* Definition du scSharedRes */
scSharedRes.prototype = {
	fSharedDom : {},
	fMaxTry    : 5,
	/* */
	
	getSharedDom: function(pUrl) {
		try{
			var vXml = this.fSharedDom[pUrl];
			// vXml("### getSharedDom : "+pUrl);
			if(vXml) {
				return vXml;
			}else{
				vTryNumber = 0;
				vMaxTry	   = 5;
				function fGetXml(){
					// debug("fGetXml n"+vTryNumber);
					vTryNumber+=1;
					try{
						/*
						var vReq = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Components.interfaces.nsIXMLHttpRequest); 
						vReq.open('GET', pUrl, false);
						vReq.send(null);  
						var vXml = vReq.responseXML;
						debug("vReq :::"+listProperties(vReq));
						debug("XML : "+vXml + ", document : " + vXml.documentElement +", getXml(vXml) : "+ (getXml(vXml)!=""));
						*/
						var vIoService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
						var vChannel = vIoService.newChannel(pUrl,null,null);
						vChannel.contentType = "text/xml";
						var vInput = vChannel.open();
						try {
							var vBuf = Components.classes["@mozilla.org/network/buffered-input-stream;1"].createInstance(Components.interfaces.nsIBufferedInputStream);
							vBuf.init(vInput, vChannel.contentLength);
							var vParser = Components.classes["@mozilla.org/xmlextras/domparser;1"].createInstance(Components.interfaces.nsIDOMParser);
							vXml = vParser.parseFromStream(vBuf, null, vChannel.contentLength, "text/xml");
						}finally {
							vInput.close();
						}
						if(!vXml && vTryNumber<vMaxTry){
							fGetXml();
						}
					}catch(e){
						if(vTryNumber<vMaxTry) fGetXml();
							else throw e;
					}
				}
				fGetXml();
				this.fSharedDom[pUrl] = vXml;
				return vXml;
			}
		} catch(e){
			debug("scSharedRes.getSharedDom(). Echec au chargement de : "+pUrl+" : "+e);
			return null;
		}
    },
    
    /**
     * Suppression du cache
     */
    reset: function() {
		try{
			this.fSharedDom = {};
		} catch(e){
			debug("scSharedRes.reset : " + e);
			return null;
		}
    },
    
    QueryInterface: function(pIID) {
            if (!pIID.equals(SHAREDRES_IID) &&
                !pIID.equals(nsISupports))
                    throw Components.results.NS_ERROR_NO_INTERFACE;
            return this;
    }
}


/* Fonctions utilitaires */
function debug(pText){
	var vConsoleService = Components.classes["@mozilla.org/consoleservice;1"].getService(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;
}

/* Module (for XPCOM registration) */
var scModule = {
    registerSelf: function(compMgr, fileSpec, location, type) {
        compMgr = compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
        compMgr.registerFactoryLocation(SHAREDRES_CID, 
                                        "scSharedRes service JS component", 
                                        SHAREDRES_CONTRACTID, 
                                        fileSpec, 
                                        location,
                                        type);
    },

    getClassObject: function(compMgr, cid, iid) {
        if (!cid.equals(SHAREDRES_CID))
            throw Components.results.NS_ERROR_NO_INTERFACE;

        if (!iid.equals(Components.interfaces.nsIFactory))
            throw Components.results.NS_ERROR_NOT_IMPLEMENTED;

        return scSharedResSvcFactory;
    },

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

/* Class Factory */
var scSharedResSvcFactory = {
    createInstance: function(outer, iid) {
        if (outer != null)
            throw Components.results.NS_ERROR_NO_AGGREGATION;
    
        if (!iid.equals(SHAREDRES_IID) &&
            !iid.equals(Components.interfaces.nsISupports))
            throw Components.results.NS_ERROR_INVALID_ARG;

        return new scSharedRes();
    }
}

/* Module initialisation */
function NSGetModule(comMgr, fileSpec) { return scModule; }

