package org.esupportail.portal.channels.CAnnuaire;
/** 
 * <p>Titre : CAnnuaire</p>
 * <p>Description : Canal de recherche dans l'annuaire</p>
 * <p>Copyright : Copyright (c) 2003</p>
 * <p>Société : esupPortail</p>
 * @author Sébatien GAUDIN
 * @version 1.0
 */


import org.jasig.portal.*;
import org.jasig.portal.services.LogService;
import org.jasig.portal.utils.*;
import org.xml.sax.*;

public class CAnnuaire implements IChannel, ICacheable {

	/****************************/
	/*Variables de programmation*/
	/****************************/

	private String annuaireSelected = null;

	private final String ETAT_FORMULAIRE = "Formulaire";
	private final String ETAT_TABLEAU_RES = "Tableau";
	private final String ETAT_FICHE_RES = "Fiche";
	private final String ETAT_RECHERCHE = "Recherche";
	private final String ETAT_REFRESH = "Actualisation";
	//attention écrit en dur dans le xsl
	private final String ETAT_DETAIL = "Detail";
	//attention écrit en dur dans le xsl

	/****************************/
	/*Variables de configuration*/
	/****************************/

	private String etat = null;

	/*fichier de configuration*/
	private final static String configFilePath =
		"/properties/channels/org_esup/CAnnuaire/CAnnuaire.xml";

	/*feuille ssl*/
	private final static String xslLocation = "CAnnuaire.ssl";

	/*temp de cache en secondes*/
	private int cacheTimeOut = 500;

	/*interface utilisateur*/
	protected userInterface UI;

	ChannelStaticData staticData = null;
	ChannelRuntimeData runtimeData = null;

	private config conf;

	//Construire le cadre
	public CAnnuaire() {
		conf = config.getInstance(configFilePath);
		UI = new userInterface(conf);
	}

	public ChannelRuntimeProperties getRuntimeProperties() {
		return new ChannelRuntimeProperties();
	}

	/** Processes layout-level events coming from the portal
	 * @param ev a portal layout event
	 */
	public void receiveEvent(PortalEvent ev) {
	}

	/** Receive static channel data from the portal
	 * @param sd static channel data
	 */
	public void setStaticData(ChannelStaticData sd) {
		this.staticData = sd;

		String serveurAuthorise = sd.getParameter("serverView");
		if ((serveurAuthorise == null) || (serveurAuthorise == ""))
			serveurAuthorise = "*";
		UI.setServerView(serveurAuthorise);
	}

	/** Receives channel runtime data from the portal and processes actions
	     * passed to it.  The names of these parameters are entirely up to the channel.
	 * @param rd handle to channel runtime data
	 */
	public void setRuntimeData(ChannelRuntimeData rd) {
		this.runtimeData = rd;

		etat = rd.getParameter("etat");

		if (etat == null)
			etat = ETAT_FORMULAIRE;

		annuaireSelected = rd.getParameter("annuaire");

	}

	/** Output channel content to the portal
	 * @param out a sax document handler
	 */
	public void renderXML(ContentHandler out) throws PortalException {
		int nbRes = 0;
		
		boolean newQuery=true;
		String uQ = runtimeData.getParameter("updateQuery");
		if (uQ!=null)newQuery=!uQ.matches("true");

		String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<RACINE>\n";

		if (etat.equals(ETAT_REFRESH)) {
			boolean setOk = UI.setServerWork(annuaireSelected);
			if (!setOk)
				xml += "<ALERT>WARN_SERVER_NOT_FOUND</ALERT>\n";
			etat = ETAT_FORMULAIRE;
		}
	

		if (UI.getServerWork() != null) {
			if (etat.equals(ETAT_FORMULAIRE)) {
				xml += UI.getForm(newQuery);
			} else {
				boolean allowSearch = false;
				if (etat.equals(ETAT_DETAIL)) {
					allowSearch =
						UI.addIdToFilter(runtimeData.getParameter("id"));
				} else {
					allowSearch = UI.updateFilter(runtimeData.getParameters());
				}
				if (!allowSearch) {
					xml += "<ALERT>WARN_FORM_NOT_FILLED</ALERT>\n";
					etat = ETAT_FORMULAIRE;
					xml += UI.getForm(newQuery);
				} else {
					xml += UI.getResultXml();
				}
			}
		} else {
			xml += "<ALERT>WARN_CONFIG_NOT_FOUND</ALERT>\n";
			etat = ETAT_FORMULAIRE;
		}
		xml += "</RACINE>\n";

		/*traitement de la chaine XML*/
		XSLT xslt = new XSLT(this);
		xslt.setXML(xml);

		String etatsuiv = "";

		/*Affectation de la feuille XSL en fonction du nombre de résultat*/
		String feuille = new String();
		if (etat.equals(ETAT_FORMULAIRE)) {
			feuille = "form";
			etatsuiv = ETAT_RECHERCHE;
		} else {

			nbRes = UI.getNbReponse();

			if (nbRes == 0) {
				feuille = "vide";
				etatsuiv = ETAT_FICHE_RES;
			} else if (
				(nbRes > 0)
					&& (nbRes
						<= conf
							.getServer(UI.getServerWork())
							.getDisplay()
							.getMaxCard())) {
				feuille = "fiche";
				etatsuiv = ETAT_FICHE_RES;
			} else if ((
				nbRes
				> conf.getServer(UI.getServerWork()).getDisplay().getMaxCard())
				/*&& (nbRes<30)*/
				) {
				feuille = "tabRes";
				etatsuiv = ETAT_TABLEAU_RES;
			}

		}

		try {
			xslt.setXSL(xslLocation, feuille, runtimeData.getBrowserInfo());
		} catch (PortalException e) {
			LogService.log(
				LogService.ERROR,
				"CAnnuaire::renderXml() : " + e.toString());
		}
		
		
		/*Envoie des paramètres au fichierXSL*/
		xslt.setStylesheetParameter("baseActionURL",runtimeData.getBaseActionURL());
		xslt.setStylesheetParameter("etat", etatsuiv);
		xslt.setStylesheetParameter("annuSelect", UI.getServerWork());
		if (UI.getServerWork() != null)xslt.setStylesheetParameter("nomId",conf.getServer(UI.getServerWork()).getQuery().getIdentifiant());
		xslt.setStylesheetParameter("numCanal",staticData.getChannelPublishId());
		if (this.staticData.getParameter("CAnnuaireServantMode") != null) {
			if (this.staticData.getParameter("returnServant").equals("single"))
				xslt.setStylesheetParameter("modeServant", "single");
			else
				xslt.setStylesheetParameter("modeServant", "multiple");
		}

		xslt.setTarget(out);
		try {
			xslt.transform();
		} catch (PortalException e) {
			LogService.log(
				LogService.ERROR,
				"CAnnuaire::renderXml() : Une erreur est survenue lors du parsing XML/XSL : "
					+ e.toString());
		}

	}

	/******************************************************************************/
	/** Genration d'une cle pour le cache
	 * 
	 * @return ChannelCacheKey cle du cache
	 */
	public ChannelCacheKey generateKey() {
		if (etat.equals(ETAT_FORMULAIRE)) {
			ChannelCacheKey k = new ChannelCacheKey();
			StringBuffer sbKey = new StringBuffer(1024);
			sbKey.append(this.getClass().getName() + " : ");
			sbKey.append("serverview:").append(UI.getServerView()).append(", ");
			sbKey.append("serverwork:").append(UI.getServerWork()).append(", ");
			sbKey.append("params:").append(runtimeData).append(", ");

			k.setKeyScope(ChannelCacheKey.SYSTEM_KEY_SCOPE);

			k.setKey(sbKey.toString());
			k.setKeyValidity(new Long(System.currentTimeMillis()));
			return k;
		}
		return null;
	}

	/**
	 * put your documentation comment here
	 * @param validity
	 * @return boolean
	 */
	public boolean isCacheValid(Object validity) {
		boolean cacheValid = false;
		if ( etat.equals(ETAT_FORMULAIRE)  ){
			if (validity instanceof Long) {
				Long oldtime = (Long) validity;
				// Si validity à moins de cacheTimeOut secondes le cache est valide
				if (System.currentTimeMillis() - oldtime.longValue()
					< cacheTimeOut * 1000) {
					cacheValid = true;
				}
			}
		}	
		return cacheValid;
	}

}
