/*
ESUP-portail is a french academic project developed under the GPL (General Public License) augmented according to the following :
A binary or source file developped by ESUP-portail can be used or compiled with products under Apache license.
The official english text of the GPL can be found here : http://www.gnu.org/licenses/gpl.html .
A non official french translation can be found here : http://www.linux-France.org/article/these/gpl.html .
The different kinds of licenses governing the products developed by the Apache foundation can be found here : http://www.apache.org/licenses .
It follows that you can as well as use download contents as well modify and redistribute them provided you respect the GPL terms.
Downloading and using such contents do not provide any guaranty.
Be sure that you have well understood the terms of the license before using the contents it covers.
The ESUP-portail distribution includes the following distributions :
    * UPortal :
      software developed by JA-SIG (Java Architecture - Special Interest Group)
      You can find the license page here : http://mis105.udel.edu/ja-sig/uportal/license.html
    * CAS :
      SSO solution developed by Yale University
      You can find the project page here : http://www.yale.edu/tp/auth
    * Cocoon :
      XML framework distributed by the Apache foundation under Apache license;
      Please find the full text here : http://cocoon.apache.org/2.1/license.html
    * Mod_dav:
      A DAV module for Apache web server
      You can find the project page here : http://www.webdav.org/mod_dav
    * IMP :
      webmail from Horde application framework
      You can find the project page here : http://www.horde.org
    * …. To be completed
*/

package org.esupportail.portal.channels.CStockage.channelAction.classic;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Vector;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.esupportail.portal.channels.CStockage.provider.ChannelResource;

import org.esupportail.portal.channels.CStockage.channelAction.AbstractDefaultRenderXml;
import org.esupportail.portal.channels.CStockage.config.ChannelConfiguration;
import org.esupportail.portal.channels.CStockage.config.Space;
import org.esupportail.portal.channels.CStockage.exception.NotAuthorizedException;
import org.esupportail.portal.channels.CStockage.exception.NotExistsResourceException;
import org.esupportail.portal.channels.CStockage.exception.PropertiesException;
import org.esupportail.portal.channels.CStockage.exception.ServerException;
import org.esupportail.portal.channels.CStockage.exception.ChannelException;
import org.esupportail.portal.channels.CStockage.provider.access.ServerAccess;

/** 
 * Id: DefaultRenderXml.java,v1.0 24 sept. 2004<br/>
 * Copyright (c) 2004 Esup Portail (www.esup-portail.org)<br/>
 * Classes: DefaultRenderXml<br/>
 * Original Author: Yohan Colmant<br/>
 * Get the XML to show the curent dir<br/>
 */
public class DefaultRenderXml extends AbstractDefaultRenderXml {
	

	/**
	 * Logger object
	 */
	protected static final Log log = LogFactory.getLog(DefaultRenderXml.class);
	
	
	
	
	/**
	 * Return the XML representing the curent dir
	 * @param spaces the visibles spaces
	 * @param currentSpace the current space used
	 * @param error the error exception
	 * @param information this information message
	 * @param config the Config object for the Channel 
	 * @return the xml generated
	 */
	public static StringBuffer getXml(ArrayList spaces, Space currentSpace, ChannelException error, String information, ChannelConfiguration config) {				
		
		ServerAccess access = currentSpace.getServerAccessObject();
		
		StringBuffer xml = new StringBuffer();
				
		int erreurInterne = -1;
		
		if (currentSpace!=null) {
			// the content of the directory
			String path = currentSpace.getPath();
		
			try {																
				
				// the action bar
				xml.append(getXmlAction(config));			
				
				// construct the ressources
				ChannelResource[] ressources = new ChannelResource[0];
				
				// we try if we are authorized
				try {
					if (access!=null)
						ressources = access.ls(path);				
				}
				catch(NotAuthorizedException e) {				
					erreurInterne = e.getErrorCode();

					// log
					if (log.isDebugEnabled()){
						log.debug("getXml"+" :: erreurInterne = "+erreurInterne);
					}
				}			
				catch(NotExistsResourceException e) {				
					erreurInterne = e.getErrorCode();

					// log
					if (log.isDebugEnabled()){
						log.debug("getXml"+" :: erreurInterne = "+erreurInterne);
					}
				}
				
				// the content of the directory	
				xml.append(getXmlContent(ressources, config));			
							
			}
			catch(ChannelException e) {			
				erreurInterne = e.getErrorCode();

				// log
				if (log.isDebugEnabled()){
					log.debug("getXml"+" :: erreurInterne = "+erreurInterne);
				}
			}		
			
			// the error bar
			xml.append(getXmlError(error, erreurInterne));
			
			// the information bar
			xml.append(getXmlInformation(information));		
			
			// the navigation bar			
			xml.append(getXmlNavigation(spaces, currentSpace));										
			
			return xml;
		}
		
		else {

			// log
			if (log.isDebugEnabled()){
				log.debug("getXml"+" :: currentSpace = "+currentSpace);
			}
			
			return getXmlError(new ServerException(), -1);
		}
	}
	
	
	
	

	
	
	
	
	
	/**
	 * Return the XML representing the curent dir
	 * @param spaces the visibles spaces
	 * @param currentSpace the current space used
	 * @param targetDirectory the directory we want to show
	 * @param error the error exception
	 * @param information this information message
	 * @param config the Config object for the Channel 
	 * @return the xml generated
	 */
	public static StringBuffer getXml(ArrayList spaces, Space currentSpace, String targetDirectory, ChannelException error, String information, ChannelConfiguration config) {				
		
		ServerAccess access = currentSpace.getServerAccessObject();
		
		StringBuffer xml = new StringBuffer();
				
		int erreurInterne = -1;
						
		// the content of the directory
		String path = currentSpace.getPath();				
		
		try {
			
			// the action bar
			xml.append(getXmlAction(config));			
			
			// construct the ressources
			ChannelResource[] ressources = new ChannelResource[0];
			
			// we try if we are authorized
			try {
				if (access!=null)
					ressources = access.ls(path, targetDirectory);
				
				// if well done, we add this directory name to the currentSpace
				currentSpace.addPathElement(targetDirectory);
			}
			catch(NotAuthorizedException e) {
				
				erreurInterne = e.getErrorCode();								

				// log
				if (log.isDebugEnabled()){
					log.debug("getXml"+" :: erreurInterne = "+erreurInterne);
				}
				
				// if not authorized, we list the last current dir
				if (access!=null)
					ressources = access.ls(path);				
			}
			
			catch(NotExistsResourceException e) {
				
				erreurInterne = e.getErrorCode();								

				// log
				if (log.isDebugEnabled()){
					log.debug("getXml"+" :: erreurInterne = "+erreurInterne);
				}
				
				// if not authorized, we list the last current dir
				if (access!=null)
					ressources = access.ls(path);				
			}
			
			// the content of the directory	
			xml.append(getXmlContent(ressources, config));							
						
		}
		catch(ChannelException e) {			
			erreurInterne = e.getErrorCode();

			// log
			if (log.isDebugEnabled()){
				log.debug("getXml"+" :: erreurInterne = "+erreurInterne);
			}
		}		
		
		// the error bar
		xml.append(getXmlError(error, erreurInterne));
		
		// the information bar
		xml.append(getXmlInformation(information));		
		
		// the navigation bar			
		xml.append(getXmlNavigation(spaces, currentSpace));										
			
		return xml;
	}
	
	
	
	
	
	
	
	/**
	 * Get the XML for the action bar
	 * @param config the Config object for the Channel
	 * @return the XML as a StringBuffer
	 * @throws PropertiesException
	 */
	private static StringBuffer getXmlAction(ChannelConfiguration config) throws PropertiesException {
		StringBuffer xmlTemp = new StringBuffer();
		
		xmlTemp.append("<ACTIONS>");
		
		xmlTemp.append("<PARENT>"+true+"</PARENT>");
		xmlTemp.append("<DIRECTORY>"+true+"</DIRECTORY>");
		xmlTemp.append("<UPLOAD>"+true+"</UPLOAD>");
		
		xmlTemp.append("<COPY>"+true+"</COPY>");
		xmlTemp.append("<MOVE>"+true+"</MOVE>");
		xmlTemp.append("<PASTE>"+true+"</PASTE>");
		xmlTemp.append("<RENAME>"+true+"</RENAME>");
		xmlTemp.append("<DELETE>"+true+"</DELETE>");
		
		xmlTemp.append("</ACTIONS>");
		
		return xmlTemp;		
	}
	
	
	
	
	/**
	 * Get the XML for the content
	 * @param ressources all the ChannelWebdavResource objects
	 * @param config the Config object for the Channel
	 * @return the XML as a StringBuffer
	 * @throws PropertiesException
	 */
	private static StringBuffer getXmlContent(ChannelResource[] ressources, ChannelConfiguration config) throws PropertiesException {
				
		StringBuffer xmlDirectory = new StringBuffer();
		StringBuffer xmlFile = new StringBuffer();
				
		for (int i=0; i<ressources.length; i++) {
			ChannelResource res = ressources[i];
			
		if (res.isCollection()) {
			//try {
				String name = res.getDisplayName();
				Vector invisibles = config.getInvisibleRegexp();                   
				boolean autorise = true;
				for (int j=0; j<invisibles.size(); j++) {
					String inv = (String)invisibles.elementAt(j);    
					
					if (name.matches(inv))                           
						autorise = false;                       
	            }    	           
				if (autorise) {	            
					String label = name.replaceAll("&","&amp;");
					label = label.replaceAll("\"","&#148;");				
					//String link = URLEncoder.encode(name,"utf-8");
					String link = label;
					link = link.replaceAll("'","\\\\'");
					xmlDirectory.append("<DIRECTORY label=\""+label+"\" link=\""+link+"\"/>");
				}
			//} 
			//catch (UnsupportedEncodingException e) {
				//log.error("getXmlContent"+" :: "+e);
			//}			
		}
		else {
			// we check if the file can be showed
			String name = res.getDisplayName();
			Vector invisibles = config.getInvisibleRegexp();                   
			boolean autorise = true;
			for (int j=0; j<invisibles.size(); j++) {
				String inv = (String)invisibles.elementAt(j);    
				
				if (name.matches(inv))                           
					autorise = false;                       
            }    	           
               	if (autorise) { 
               		// date format
               		long d = res.getLastModified();        	          
               		Calendar cal = Calendar.getInstance();
               		
               		cal.setTimeInMillis(d);
               		String date = cal.get(Calendar.DATE)+"";
               		if (date.length()==1)
               			date = "0"+date;
               		String month = (cal.get(Calendar.MONTH)+1)+"";
               		if (month.length()==1)
               			month = "0"+month;
               		String year = cal.get(Calendar.YEAR)+"";	                       
               		String hour = (cal.get(Calendar.HOUR_OF_DAY))+"";
               		
               		if (hour.length()==1)
               			hour = "0"+hour;
               		String minute = cal.get(Calendar.MINUTE)+"";
               		if (minute.length()==1)
               			minute = "0"+minute;
               		
               		// length format
               		long intLength = (long)res.getContentLength();	                   		      			
            		String length = getLengthFormat(intLength);
               		
               		

               		//try {
               			
           		xmlFile.append("<FILE ");
           		String label = name.replaceAll("&","&amp;");
				label = label.replaceAll("\"","&#148;");
           		xmlFile.append("label=\""+label+"\" ");
           		//String labelDownload = URLEncoder.encode(name,"utf-8");
           		String labelDownload = label;
           		labelDownload = labelDownload.replaceAll("'","\\\\'");
           		xmlFile.append("label_download=\""+labelDownload+"\" ");
           		xmlFile.append("mime=\""+res.getContentType()+"\" ");
           		xmlFile.append("weight=\""+length+"\" ");
           		xmlFile.append("dateLastUpdate=\""+date+"\" ");
           		xmlFile.append("monthLastUpdate=\""+month+"\" ");
           		xmlFile.append("yearLastUpdate=\""+year+"\" ");
           		xmlFile.append("hourLastUpdate=\""+hour+"\" ");
           		xmlFile.append("minuteLastUpdate=\""+minute+"\" />");
				//} catch (UnsupportedEncodingException e1) {
					//log.error("getXmlContent"+" :: "+e1);
				//}
				 
               }
           }
		}		
		
		StringBuffer xml = new StringBuffer();
		xml.append("<CONTENT>");										
		xml.append(xmlDirectory);
		xml.append(xmlFile);
		xml.append("</CONTENT>");
		return xml;
	}
	
	
}
