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

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.esupportail.portal.channels.CStockage.channelAction.BufferAction;
import org.esupportail.portal.channels.CStockage.channelAction.Constants;
import org.esupportail.portal.channels.CStockage.channelAction.injac.DirectoryProperties;
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.Space;
import org.esupportail.portal.channels.CStockage.exception.CancelException;
import org.esupportail.portal.channels.CStockage.exception.EmptyClipboardException;
import org.esupportail.portal.channels.CStockage.exception.InjacDocumentException;
import org.esupportail.portal.channels.CStockage.exception.MoveForPublishException;
import org.esupportail.portal.channels.CStockage.exception.NoneSelectedResourceException;
import org.esupportail.portal.channels.CStockage.exception.NotEditorInSpaceException;
import org.esupportail.portal.channels.CStockage.exception.NotWriterInSpaceException;
import org.esupportail.portal.channels.CStockage.exception.PasteDeletedResourceException;
import org.esupportail.portal.channels.CStockage.exception.PublishInBadSpaceException;
import org.esupportail.portal.channels.CStockage.exception.ChannelException;
import org.jasig.portal.ChannelRuntimeData;

/**
 * Id: DocumentPublicationAction.java,v 1.0 27 oct. 2004
 * Copyright (c) 2004 Esup Portail (www.esup-portail.org)
 * Classes: DocumentPublicationAction
 * Original Author: Yohan Colmant
 * Action for the document publication
 */
public class DocumentPublicationAction {



	/**
	 * Logger object
	 */
	protected static final Log log = LogFactory.getLog(DocumentPublicationAction.class);
	
	


	/**
	 * Generate the XML when we ask a publish confirmation
	 * @param runtimeData the channel runtimedata object
	 * @param buffer the buffer used for the clipboard
	 * @param stylesheet the channel stylesheet we are going to use
	 * @param spaces the spaces list
	 * @param metadataToSet the metatada list we want to set
	 * @param userPortalLogin the user portal login
	 * @param userGroups the user portal groups
	 * @param currentSpace the current space
	 * @param directoryProperties the current directory properties
	 * @return the XML String for this mod
	 * @throws ChannelException
	 */
	public static StringBuffer renderXmlConfirmPublish(ChannelRuntimeData runtimeData, BufferAction buffer, StringBuffer stylesheet, ArrayList spaces, Vector metadataToSet, String userPortalLogin, Vector userGroups, Space currentSpace, DirectoryProperties directoryProperties) throws ChannelException {
		
		String[] files = runtimeData.getParameterValues("listeFic");

		// we want to publish a document for the first time
		if (files == null) {

			// log
			if (log.isDebugEnabled()){
				log.debug("renderXmlConfirmPublish"+" :: publish a new document");
			}
			
			return renderXmlConfirmPublishNewDocument(buffer, currentSpace, directoryProperties);
		}
		
		// we want to publish one more time a document
		else {	

			// log
			if (log.isDebugEnabled()){
				log.debug("renderXmlConfirmPublish"+" :: publish an old document again");
			}
			
			return renderXmlConfirmPublishOldDocument(files, userPortalLogin, currentSpace);		
		}
		
		
	
	}
	
	
	
	
	/**
	 * Generate the XML when we ask a publish confirmation of a new document
	 * @param buffer the buffer used for the clipboard
	 * @param currentSpace the current space
	 * @param directoryProperties the current directory properties
	 * @return the XML String for this mod
	 * @throws ChannelException
	 */	
	private static StringBuffer renderXmlConfirmPublishNewDocument(BufferAction buffer, Space currentSpace, DirectoryProperties directoryProperties) throws ChannelException {		

		// if the user is not a writer, we throw an excpetion
		if (!directoryProperties.isUserWriter()) {
			throw new NoneSelectedResourceException();
		}
		
		// Xml generated
		StringBuffer xml = new StringBuffer();
		
		Vector clipboardFrom = buffer.getClipboard();
		
		// if the clipboard is empty
		if (clipboardFrom== null || clipboardFrom.size()==0) {
			EmptyClipboardException e = new EmptyClipboardException();

			// log
			if (log.isDebugEnabled()){
				log.debug("renderXmlConfirmPublishNewDocument"+" :: clipboard is empty, EmptyClipboardException");
			}
			
			throw e;	
		}
		
		// if select "move"
		if (buffer.getClipboardParameter().equals(Constants.MOVE_MODE)) {
			MoveForPublishException e = new MoveForPublishException();

			// log
			if (log.isDebugEnabled()){
				log.debug("renderXmlConfirmPublishNewDocument"+" :: we can not select \"move\" to set the clipboard, MoveForPublishException");
			}
			
			throw e;	
		}
		
		// we check if we have the rights ACL to paste here
		try {			
			Vector clipboardTo = new Vector(clipboardFrom.size());
			for (int i=0; i<clipboardFrom.size(); i++) {
				String name = (String)clipboardFrom.elementAt(i);
				
				// if directory
				if (buffer.getClipboardSpace().getServerAccessObject().isDirectory(name, buffer.getClipboardPath())) {
					clipboardTo.addElement(name);
				}
				else {
					clipboardTo.addElement(DirectoryProperties.getResourceNameWithoutLastDot(name));
				}
			}
			currentSpace.getServerAccessObject().canPaste(buffer.getClipboardSpace(), currentSpace.getKey(), buffer.getClipboardPath(), clipboardFrom, clipboardTo, currentSpace.getCurrentPath());
		}
		catch (PasteDeletedResourceException e) {
			buffer.setClipboard(null);
			buffer.setClipboardParameter(null);
			buffer.setClipboardPath(null);	
			buffer.setTypes(null);
									
			// log
			if (log.isDebugEnabled()){
				log.debug("renderXmlConfirmPublishNewDocument"+" :: "+e);
			}
			
			throw e;
		}
		
		
		// we check where we want to paste, and which role we have here
		String directoryType = directoryProperties.getType();//MetaDataManager.getDirectoryType(currentSpace, currentSpace.getCurrentPath());
		
		// if we are in a space
		if (directoryType.equals(MetaDataConstants.INJAC_TYPE_SPACE)) {
			
			// if we are editor here
			boolean editor = directoryProperties.isUserEditor();
			if (editor) {
			
				// if we are editor here
				boolean writer = directoryProperties.isUserWriter();
				if (writer) {

					// for each clipboard element
					for (int i=0; i<clipboardFrom.size(); i++) {
						
						String clipboardSelection = (String) clipboardFrom.elementAt(i);
						String clipboardPath = buffer.getClipboardPath();
						
						clipboardSelection = clipboardSelection.replaceAll("&","&amp;");
						clipboardSelection = clipboardSelection.replaceAll("\"","&#148;");
						clipboardPath = clipboardPath.replaceAll("&","&amp;");
						clipboardPath = clipboardPath.replaceAll("\"","&#148;");
						
						xml.append("<DOCUMENT name=\""+clipboardSelection+"\" path=\""+clipboardPath+"\" type=\""+MetadataManagerAction.PUBLISH_DOC_FROM_CLIPBOARD+"\" />");
					}
				}
				
				// if we are not writer
				else {
					NotWriterInSpaceException e = new NotWriterInSpaceException();

					// log
					if (log.isDebugEnabled()){
						log.debug("renderXmlConfirmPublishNewDocument"+" :: NotWriterInSpaceException");
					}
					
					throw e;
				}
			}
			
			// if we are not editor
			else {
				NotEditorInSpaceException e = new NotEditorInSpaceException();

				// log
				if (log.isDebugEnabled()){
					log.debug("renderXmlConfirmPublishNewDocument"+" :: NotEditorInSpaceException");
				}
				
				throw e;
			}
		}
		
		// we are not in a space
		else {
			PublishInBadSpaceException e = new PublishInBadSpaceException();

			// log
			if (log.isDebugEnabled()){
				log.debug("renderXmlConfirmPublishNewDocument"+" :: SubmitInBadSpaceException");
			}
			
			throw e;
		}		
			
		return xml;							
	}
	
	
	
	
	
	/**
	 * Generate the XML when we ask a publish confirmation of an existing document
	 * @param files the files we want to submit again
	 * @param userPortalLogin the user portal login
	 * @param currentSpace the current space
	 * @return the XML String for this mod
	 * @throws ChannelException
	 */
	private static StringBuffer renderXmlConfirmPublishOldDocument(String[] files, String userPortalLogin, Space currentSpace) throws ChannelException {
		
		// Xml generated
		StringBuffer xml = new StringBuffer();
		
		// if not selected
		if (files == null || files.length==0) {						
			NoneSelectedResourceException e = new NoneSelectedResourceException();

			// log
			if (log.isDebugEnabled()){
				log.debug("renderXmlConfirmPublishOldDocument"+" :: NoneSelectedResourceException");
			}
			
			throw e;			
		}
		
		// if too much selected
		/*if (files.length>1) {			
			TooMuchSelectedException e = new TooMuchSelectedException();

			// log
			if (log.isDebugEnabled()){
				log.debug("renderXmlConfirmPublishOldDocument"+" :: TooMuchSelectedException");
			}
			
			throw e;			
		}*/
		
		// for each selected document
		for (int i=0; i<files.length; i++) {
		
			// if one resource selected
			String selectionName = files[i];
			String selectionPath = currentSpace.getCurrentPath();
			String selectionFullPath = selectionPath+selectionName;
			
			// check if the resource is an injac document
			String documentType = MetaDataManager.getDirectoryType(currentSpace, selectionFullPath);
			if (documentType.equals(MetaDataConstants.INJAC_TYPE_DOCUMENT)) {
				
				// check if the resource state is "waiting" or "expired" or "refused"
				String documentState = MetaDataManager.getDocumentState(currentSpace, selectionFullPath);
				if (documentState.equals(MetaDataConstants.DOCUMENT_WAITING_STATE) || documentState.equals(MetaDataConstants.DOCUMENT_EXPIRED_STATE) || documentState.equals(MetaDataConstants.DOCUMENT_REFUSED_STATE)) {
					selectionName = selectionName.replaceAll("&","&amp;");
					selectionName = selectionName.replaceAll("\"","&#148;");
					selectionPath = selectionPath.replaceAll("&","&amp;");
					selectionPath = selectionPath.replaceAll("\"","&#148;");
					
					xml.append("<DOCUMENT name=\""+selectionName+"\" path=\""+selectionPath+"\" type=\""+MetadataManagerAction.PUBLISH_EDITED_DOC+"\" />");
				}
				
				else {			
					InjacDocumentException e = new InjacDocumentException();
	
					// log
					if (log.isDebugEnabled()){
						log.debug("renderXmlConfirmPublishOldDocument"+" :: InjacDocumentException");
					}
					
					throw e;				
				}						
				
			}
			
			else {
				InjacDocumentException e = new InjacDocumentException();
	
				// log
				if (log.isDebugEnabled()){
					log.debug("renderXmlConfirmPublishOldDocument"+" :: InjacDocumentException");
				}
				
				throw e;			
			}
		
		}
			
		return xml;							
	}
	
	
	
	
	
	
	
	/**
	 * Generate the XML String and publish the document
	 * @param runtimeData the runtime data channel object
	 * @param stylesheet the stylesheet we are about to use
	 * @param spaces the default spaces
	 * @param metadataToSet the metadata list we want to set
	 * @param userPortalLogin the user portal login
	 * @param userGroups the user portal groups
	 * @param currentSpace the current space
	 * @param directoryProperties the current directory properties
	 * @param buffer the buffer used for example for the clipboard
	 * @param currentSortType The current and default sort type for the resources
	 * @return the XML String for this mod
	 * @throws ChannelException
	 */
	public static StringBuffer publish(ChannelRuntimeData runtimeData, StringBuffer stylesheet, ArrayList spaces, Vector metadatasToSet, String userPortalLogin, Vector userGroups, Space currentSpace, DirectoryProperties directoryProperties, BufferAction buffer, String currentSortType) throws ChannelException {
		String submit = runtimeData.getParameter("Submit_pub");
		
		// if submit
		if (submit != null) {			
			return MetadataManagerAction.renderXmlMetadataManager(runtimeData, stylesheet, spaces, metadatasToSet, userPortalLogin, userGroups, currentSpace, directoryProperties, buffer, currentSortType);			
		}
		
		// if cancel
		else {			
			CancelException e = new CancelException();

			// log
			if (log.isDebugEnabled()){
				log.debug("publish"+" :: CancelException");
			}
			
			throw e;
		}				
				
	}
	
	
	
	
	
	
	
	
}
