/*
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.injac;

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.channelAction.AbstractDefaultRenderXml;
import org.esupportail.portal.channels.CStockage.channelAction.injac.metadata.MetaDataConstants;
import org.esupportail.portal.channels.CStockage.channelAction.injac.metadata.MetaDataManager;
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.ChannelResource;
import org.esupportail.portal.channels.CStockage.provider.access.ServerAccess;


/**
 * Id: DefaultRenderXml.java,v 1.0 27 sept. 2004
 * Copyright (c) 2004 Esup Portail (www.esup-portail.org)
 * Classes: DefaultRenderXml
 * Original Author: Yohan Colmant
 * 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
	 * @param userPortalLogin the user portal login
	 * @param userGroups the user portal groups
	 * @param directoryProperties 
	 * @return the xml generated
	 */
	public static StringBuffer getXml(ArrayList spaces, Space currentSpace, ChannelException error, String information, ChannelConfiguration config, String userPortalLogin, Vector userGroups, DirectoryProperties directoryProperties) {				
		
		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(currentSpace, userPortalLogin, userGroups, directoryProperties));			
				
				// 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) {
					if (log.isDebugEnabled()){
						log.debug("getXml"+" :: "+e);
					}
					erreurInterne = e.getErrorCode();											
				}			
				catch(NotExistsResourceException e) {
					if (log.isDebugEnabled()){
						log.debug("getXml"+" :: "+e);
					}
					erreurInterne = e.getErrorCode();																			
				}
				
				// the content of the directory	
				xml.append(getXmlContent(currentSpace, ressources, config, userPortalLogin, userGroups, directoryProperties));			
							
			}
			catch(ChannelException e) {			
				erreurInterne = e.getErrorCode();
				if (log.isDebugEnabled()){
					log.debug("getXml"+" :: "+e);
				}
			}		
			
			// 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 {
			return getXmlError(new ServerException(), -1);
		}
	}
	
	
	
	
	
	/**
	 * Get the XML for the action bar
	 * @param currentSpace the current space used
	 * @param userPortalLogin the user portal login
	 * @param userGroups the user portal groups
	 * @param directoryProperties the current directory properties
	 * @return the XML as a StringBuffer
	 * @throws PropertiesException
	 * @throws ServerException
	 */
	private static StringBuffer getXmlAction(Space currentSpace, String userPortalLogin, Vector userGroups, DirectoryProperties directoryProperties) throws PropertiesException, ServerException {
		
		ServerAccess access = currentSpace.getServerAccessObject();
		
		String fullPath = currentSpace.getPath();		
		boolean manager = directoryProperties.isUserManager();
		boolean writer = directoryProperties.isUserWriter();
		boolean editor = directoryProperties.isUserEditor();
		
		String directoryType = directoryProperties.getType();
		if (directoryType==null)
			directoryType="";
		
		StringBuffer xmlTemp = new StringBuffer();
		
		xmlTemp.append("<ACTIONS>");		
		xmlTemp.append("<PARENT>"+true+"</PARENT>");
		
		// if we are not in a space
		if (!directoryType.equals(MetaDataConstants.INJAC_TYPE_SPACE)) {
			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>");
		}	
		
		else {
			// if not writer, not editor, not manager
			if ( writer || manager || editor ) {				
			
				xmlTemp.append("<RENAME>"+true+"</RENAME>");
				xmlTemp.append("<DELETE>"+true+"</DELETE>");
			
			}
		}
				
		// if we are editor or writer
		if (writer || editor) {
			xmlTemp.append("<UNPUBLISH>"+true+"</UNPUBLISH>");
			xmlTemp.append("<METADATA>"+true+"</METADATA>");
		}
		
		// if we are writer
		if (writer && !editor) {
			xmlTemp.append("<SUBMIT>"+true+"</SUBMIT>");
		}
		
		// if we are editor
		if (editor) {
			xmlTemp.append("<PUBLISH>"+true+"</PUBLISH>");		
			xmlTemp.append("<REFUSE>"+true+"</REFUSE>");
		}				
		
		// if the current dir is a space				
		if (directoryType.equals(MetaDataConstants.INJAC_TYPE_SPACE)) {
			
			// if the user is manager in this space			
			if (manager) {			
				xmlTemp.append("<ADMIN>"+true+"</ADMIN>");
				xmlTemp.append("<SPACE>"+true+"</SPACE>");
			}
		}
		
		
		xmlTemp.append("</ACTIONS>");
		
		return xmlTemp;		
	}
	
	
	
	/**
	 * Get the XML for the content
	 * @param currentSpace the current space used
	 * @param ressources all the ChannelWebdavResource objects
	 * @param config the Config object for the Channel
	 * @param userPortalLogin the user portal login
	 * @param userGroups the user portal groups
	 * @param directoryProperties the current directory properties
	 * @return the XML as a StringBuffer
	 * @throws PropertiesException
	 * @throws ServerException
	 */
	private static StringBuffer getXmlContent(Space currentSpace, ChannelResource[] ressources, ChannelConfiguration config, String userPortalLogin, Vector userGroups, DirectoryProperties directoryProperties) throws PropertiesException, ServerException {
				
		StringBuffer xmlDirectory = new StringBuffer();
		StringBuffer xmlFile = new StringBuffer();
		
		String path = currentSpace.getPath();
		
		boolean userIsWriterOnSpace = directoryProperties.isUserWriter();
		boolean userIsEditorOnSpace = directoryProperties.isUserEditor();	
		
		
		for (int i=0; i<ressources.length; i++) {
			ChannelResource res = ressources[i];		
			
			// if the resource is a collection
			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 fullPath = path+name;
					
						// the type: document, space ?
						String type = MetaDataManager.getDirectoryType(currentSpace, fullPath);
						
						// check the state for the document
						String state = null;					
						if (type!=null && type.equals(MetaDataConstants.INJAC_TYPE_DOCUMENT)) {							
							state = MetaDataManager.getDocumentState(currentSpace, fullPath);							
						}
						
						String label = name.replaceAll("&","&amp;");
						label = label.replaceAll("\"","&#148;");					
						
						//String link = URLEncoder.encode(name,"utf-8");
						String link = label;
						link = link.replaceAll("'","\\\\'");
						
						// no type, we show default directory
						if (type == null || type.equals("")) {
							xmlDirectory.append("<DIRECTORY label=\""+label+"\" link=\""+link+"\"   />");
						}
						else {
							
							// if space type
							if (type.equals(MetaDataConstants.INJAC_TYPE_SPACE)) {
								xmlDirectory.append("<DIRECTORY label=\""+label+"\" link=\""+link+"\" state=\""+type+"\"  />");														
							}
							
							// if type document
							else {
								
								// if writer or editor on space
								if (userIsWriterOnSpace || userIsEditorOnSpace) {
									xmlDirectory.append("<DIRECTORY label=\""+label+"\" link=\""+link+"\" state=\""+state+"\"  />");
								}
							
							}
						}
					}
					
					
					/*
					if (type == null) {
						state = null;
					}					
					else {
						if (type.equals(MetaDataConstants.INJAC_TYPE_SPACE)) {
							state = type;
						}
						else {
							if (type.equals(MetaDataConstants.INJAC_TYPE_DOCUMENT)) {							
								state = MetaDataManager.getDocumentState(access, fullPath);							
							}
						}
					}
					
					if (state!=null) {						
						if ((state.equals(MetaDataConstants.INJAC_TYPE_SPACE)) || ( (!state.equals(MetaDataConstants.INJAC_TYPE_SPACE)) && (userIsWriterOnSpace || userIsEditorOnSpace)))						
							xmlDirectory.append("<DIRECTORY label=\""+name+"\" link=\""+URLEncoder.encode(res.getDisplayName(),"utf-8")+"\" state=\""+state+"\"  />");						
					}
					else {						
						if (userIsWriterOnSpace || userIsEditorOnSpace)
							xmlDirectory.append("<DIRECTORY label=\""+name+"\" link=\""+URLEncoder.encode(res.getDisplayName(),"utf-8")+"\"   />");
					}
					*/
					
				//} 
				//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;
	}
	
	

}
