/*
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.ChannelAction;
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.MoveForSubmitException;
import org.esupportail.portal.channels.CStockage.exception.NoneSelectedResourceException;
import org.esupportail.portal.channels.CStockage.exception.NotAuthorizedException;
import org.esupportail.portal.channels.CStockage.exception.NotWriterInSpaceException;
import org.esupportail.portal.channels.CStockage.exception.PasteDeletedResourceException;
import org.esupportail.portal.channels.CStockage.exception.SubmitInBadSpaceException;
import org.esupportail.portal.channels.CStockage.exception.TooMuchSelectedException;
import org.esupportail.portal.channels.CStockage.exception.ChannelException;
import org.jasig.portal.ChannelRuntimeData;

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


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


	/**
	 * Generate the XML when we ask a submit 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 channel 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 renderXmlConfirmSubmit(ChannelRuntimeData runtimeData, BufferAction buffer, StringBuffer stylesheet, ArrayList spaces, ArrayList 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("renderXmlConfirmSubmit"+" :: submit a new document");
			}
			
			return renderXmlConfirmSubmitNewDocument(buffer, currentSpace, directoryProperties);
		}
		
		// we want to publish one more time a document
		else {		

			// log
			if (log.isDebugEnabled()){
				log.debug("renderXmlConfirmSubmit"+" :: submit an old document again");
			}
			
			return renderXmlConfirmSubmitOldDocument(files, userPortalLogin, currentSpace);		
		}
		
		
	
	}
	
	
	
	
	/**
	 * Generate the XML when we ask a submit 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 renderXmlConfirmSubmitNewDocument(BufferAction buffer, Space currentSpace, DirectoryProperties directoryProperties) throws ChannelException {		

		// Xml generated
		StringBuffer xml = new StringBuffer();
		
		Vector clipboard = buffer.getClipboard();
		
		// if the clipboard is empty
		if (clipboard== null || clipboard.size()==0) {
			EmptyClipboardException e = new EmptyClipboardException();

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

			// log
			if (log.isDebugEnabled()){
				log.debug("renderXmlConfirmSubmitNewDocument"+" :: we can not select \"move\" to set the clipboard, MoveForSubmitException");
			}
			
			throw e;	
		}
		
		// we check if we have the rights ACL to paste here
		try {			
			currentSpace.getServerAccessObject().canPaste(buffer.getClipboardSpace(), currentSpace.getKey(), buffer.getClipboardPath(), clipboard, currentSpace.getCurrentPath());
		}
		catch (PasteDeletedResourceException e) {
			buffer.setClipboard(null);
			buffer.setClipboardParameter(null);
			buffer.setClipboardPath(null);						
						
			// log
			if (log.isDebugEnabled()){
				log.debug("renderXmlConfirmSubmitNewDocument"+" :: the resource has been deleted, PasteDeletedResourceException");
			}
			
			throw e;
		}
		
		
		// we check where we want to paste, and which role we have here
		
		String directoryType = MetaDataManager.getDirectoryType(currentSpace, currentSpace.getCurrentPath());
		
		// if we are in a space
		if (directoryType.equals(MetaDataConstants.INJAC_TYPE_SPACE)) {
			
			// if we are writer here
			boolean writer = directoryProperties.isUserWriter();
			if (writer) {
			
				// if the clipboard is single
				if (clipboard.size() == 1) {

					String clipboardSelection = (String) clipboard.elementAt(0);
					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.EDIT_DOC_FROM_CLIPBOARD+"\" />");
				}

				// if there are more than one selected source
				else {
					TooMuchSelectedException e = new TooMuchSelectedException();
					
					// log
					if (log.isDebugEnabled()){
						log.debug("renderXmlConfirmSubmitNewDocument"+" :: TooMuchSelectedException");
					}
					
					throw e;
				}
			}
			
			// if we are not writer
			else {
				NotWriterInSpaceException e = new NotWriterInSpaceException();

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

			// log
			if (log.isDebugEnabled()){
				log.debug("renderXmlConfirmSubmitNewDocument"+" :: SubmitInBadSpaceException");
			}
			
			throw e;
		}		
			
		return xml;							
	}
	
	
	
	
	
	/**
	 * Generate the XML when we ask a submit 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 renderXmlConfirmSubmitOldDocument(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("renderXmlConfirmSubmitOldDocument"+" :: NoneSelectedResourceException");
			}
			
			throw e;			
		}
		
		// if too much selected
		if (files.length>1) {			
			TooMuchSelectedException e = new TooMuchSelectedException();

			// log
			if (log.isDebugEnabled()){
				log.debug("renderXmlConfirmSubmitOldDocument"+" :: TooMuchSelectedException");
			}
			
			throw e;			
		}
		
		// if one resource selected
		String selectionName = files[0];
		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 "refused" or "expired"
			String documentState = MetaDataManager.getDocumentState(currentSpace, selectionFullPath);
			if (documentState.equals(MetaDataConstants.DOCUMENT_EXPIRED_STATE) || documentState.equals(MetaDataConstants.DOCUMENT_REFUSED_STATE)) {

				// if we are not the document owner
				if (!ChannelAction.isUserDocumentOwner(selectionFullPath, currentSpace, userPortalLogin)) {					
					NotAuthorizedException e = new NotAuthorizedException();

					// log
					if (log.isDebugEnabled()){
						log.debug("renderXmlConfirmSubmitOldDocument"+" :: NotAuthorizedException");
					}
					
					throw e;
				}
				
				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.EDIT_OLD_DOC+"\" />");		
				
			}
			
			else {			
				InjacDocumentException e = new InjacDocumentException();

				// log
				if (log.isDebugEnabled()){
					log.debug("renderXmlConfirmSubmitOldDocument"+" :: InjacDocumentException");
				}
				
				throw e;				
			}
						
		}
		
		else {
			InjacDocumentException e = new InjacDocumentException();

			// log
			if (log.isDebugEnabled()){
				log.debug("renderXmlConfirmSubmitOldDocument"+" :: InjacDocumentException");
			}
			
			throw e;			
		}		
			
		return xml;							
	}
	
	
	
	
	
	
	
	/**
	 * Generate the XML String and submit the document
	 * @param runtimeData the runtime data channel object
	 * @param stylesheet the stylesheet we are about to use
	 * @param spaces the spaces list
	 * @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 submit(ChannelRuntimeData runtimeData, StringBuffer stylesheet, ArrayList spaces, ArrayList metadataToSet, String userPortalLogin, Vector userGroups, Space currentSpace, DirectoryProperties directoryProperties, BufferAction buffer, String currentSortType) throws ChannelException {
		String submitConfirm = runtimeData.getParameter("Submit_sub");
		String cancelConfirm = runtimeData.getParameter("Cancel_sub");
		
		// if submit
		if (submitConfirm != null) {			
			return MetadataManagerAction.renderXmlMetadataManager(runtimeData, stylesheet, spaces, metadataToSet, userPortalLogin, userGroups, currentSpace, directoryProperties, buffer, currentSortType);			
		}
		
		// if cancel
		else {			
			CancelException e = new CancelException();

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