/**
 * FTPDownloadMessageHandler.java
 * Created on Mar 1, 2007
 * (C) Copyright TANDBERG Television Ltd.
 */
package com.tandbergtv.workflow.webservice.filesubsystem.messagehandler;

import org.apache.log4j.Logger;

import com.tandbergtv.workflow.message.WorkflowMessage;
import com.tandbergtv.workflow.message.WorkflowPayload;
import com.tandbergtv.workflow.webservice.filesubsystem.FTPConfigurationManager;
import com.tandbergtv.workflow.webservice.filesubsystem.FileManagementException;

/**
 * @author Vlada Jakobac
 * @author Raj Prakash
 *
 */
public class FTPMessageHandler extends FileManagementMessageHandler
{

	private static final Logger logger = Logger.getLogger(FTPMessageHandler .class);
	
	/**
	 * 
	 */
	public FTPMessageHandler()
	{
		super();
		// TODO Auto-generated constructor stub
	}

	
	//Expected ftp url format: ftp://host/path
	
	private static final String FTP_URL_PREFIX = "ftp://";
	
	/**
	 * @see com.tandbergtv.workflow.webservice.filesubsystem.messagehandler.AbstractMessageHandler#performOperation(com.tandbergtv.workflow.message.WorkflowMessage,
	 *      com.tandbergtv.workflow.message.WorkflowMessage)
	 */
	@Override
	protected void performOperation(WorkflowMessage message, WorkflowMessage response)
			throws Exception
	{
		//get user name & password from configuration
		//based on whether the ftp url is in sourcePath or destinationPath, download or upload.
		
		WorkflowPayload payload = (WorkflowPayload) message.getPayload();
		String sourcePath = payload.getValue(MessageParameters.SOURCE_PATH);
		String destinationPath = payload.getValue(MessageParameters.DESTINATION_PATH);
		
		//upload or download based on if the ftp url is in source path or destination path
		boolean download = sourcePath.toLowerCase().startsWith(FTP_URL_PREFIX);
		boolean upload = destinationPath.toLowerCase().startsWith(FTP_URL_PREFIX);
		
		if (download && upload)
			throw new FileManagementException("Only one of the source or the destination paths could be an FTP path.");
		if (!download && !upload)
			throw new FileManagementException("Either the source or the destination path must be a valid FTP path.");
		
		if(download) //download
		{
			if (sourcePath.equalsIgnoreCase(FTP_URL_PREFIX))
				throw new FileManagementException("The host and file name must be specified in the source FTP path:" + sourcePath);
			//get host
			String host = getHostFromFtpUrl(sourcePath);
			//get username and password from configuration
			String userName = FTPConfigurationManager.getInstance().getUserName(host);
			String password = FTPConfigurationManager.getInstance().getPassword(host);
			String sourceFilePath = getFilePathFromFtpUrl(sourcePath);
			logger.debug(sourceFilePath + " | " + destinationPath + " | " + host + " | " + userName + " | " + password);
			this.getService().ftpDownload(sourceFilePath, destinationPath, host, userName, password);
			logger.debug("Finished downloading");
		}
		else //upload
		{
			if (destinationPath.equalsIgnoreCase(FTP_URL_PREFIX))
				throw new FileManagementException("The host name must be specified in the destination FTP path:" + destinationPath);
			//get host
			String host = getHostFromFtpUrl(destinationPath);
			//get username and password from configuration
			String userName = FTPConfigurationManager.getInstance().getUserName(host);
			String password = FTPConfigurationManager.getInstance().getPassword(host);
			String destinationFilePath = getFilePathFromFtpUrl(destinationPath);
			logger.debug(sourcePath + " | " + destinationFilePath + " | " + host + " | " + userName + " | " + password);
			this.getService().ftpUpload(sourcePath, destinationFilePath, host, userName, password);
			logger.debug("Finished uploading");
		}
		
	}
	
	private String getHostFromFtpUrl(String ftpUrl) 
	{
		int ftpPrefixLength = FTP_URL_PREFIX.length();
		int index = ftpUrl.indexOf('/', ftpPrefixLength);
		if (index != -1)
			return ftpUrl.substring(ftpPrefixLength, index);
		else 
			return ftpUrl.substring(ftpPrefixLength);
	}
	
	private String getFilePathFromFtpUrl(String ftpUrl) throws FileManagementException
	{
		int index = ftpUrl.indexOf('/', FTP_URL_PREFIX.length());
		if (index != -1)
			return ftpUrl.substring(index);
		else
			return "/";
	}

	
}
