package cdac.medinfo.sdk.hl7282.tool.client;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;

import cdac.medinfo.sdk.hl7282.baselibs.messagedictionary.MessageMapReader;
import cdac.medinfo.sdk.hl7282.baselibs.messages.ACK;
import cdac.medinfo.sdk.hl7282.baselibs.messages.IMessageRecepient;
import cdac.medinfo.sdk.hl7282.baselibs.messages.IMessageSource;
import cdac.medinfo.sdk.hl7282.baselibs.messages.Message;
import cdac.medinfo.sdk.hl7282.baselibs.messages.MessageFactory;
import cdac.medinfo.sdk.hl7282.baselibs.parserserializer.HL7Parser;
import cdac.medinfo.sdk.hl7282.baselibs.parserserializer.HL7Serializer;
import cdac.medinfo.sdk.hl7282.baselibs.segments.MSA;
import cdac.medinfo.sdk.hl7282.baselibs.segments.MSH;
import cdac.medinfo.sdk.hl7282.baselibs.segments.Segment;
import cdac.medinfo.sdk.hl7282.commoninterface.ISegmentSet;
import cdac.medinfo.sdk.hl7282.commoninterface.ISingleCollection;
import cdac.medinfo.sdk.hl7282.exceptions.MessageNotSupportedException;
import cdac.medinfo.sdk.hl7282.hl7model.messages.applicationmanagement.AppMgtRecepient;
import cdac.medinfo.sdk.hl7282.hl7model.messages.clinicallaboratoryautomation.ClinicalLabAutoRecepient;
import cdac.medinfo.sdk.hl7282.hl7model.messages.financialmanagement.FinancialRecepient;
import cdac.medinfo.sdk.hl7282.hl7model.messages.masterfiles.MasterFileRecepient;
import cdac.medinfo.sdk.hl7282.hl7model.messages.medicalrecords.MediRecRecepient;
import cdac.medinfo.sdk.hl7282.hl7model.messages.observationreporting.ObsvRepRecepient;
import cdac.medinfo.sdk.hl7282.hl7model.messages.orderentry.OrderEntryRecepient;
import cdac.medinfo.sdk.hl7282.hl7model.messages.patientadministration.ADTRecepient;
import cdac.medinfo.sdk.hl7282.hl7model.messages.patientadministration.ADTSource;
import cdac.medinfo.sdk.hl7282.hl7model.messages.patientcare.PatientCareRecepient;
import cdac.medinfo.sdk.hl7282.hl7model.messages.patientreferral.PatientRefRecepient;
import cdac.medinfo.sdk.hl7282.hl7model.messages.personnelmanagement.PersonalMgmtRecepient;
import cdac.medinfo.sdk.hl7282.hl7model.messages.scheduling.SchedulingRecepient;
import cdac.medinfo.sdk.hl7282.hl7net.auxiliaryprotocol.batch.BatchAgent;
import cdac.medinfo.sdk.hl7282.hl7net.auxiliaryprotocol.fragment.FragmentAgent;
import cdac.medinfo.sdk.hl7282.hl7net.auxiliaryprotocol.transactionhandler.TransactionHandler;
import cdac.medinfo.sdk.hl7282.hl7net.commons.IBatchProcessor;
import cdac.medinfo.sdk.hl7282.hl7net.commons.IFragmentProcessor;
import cdac.medinfo.sdk.hl7282.hl7net.commons.IHL7Batch;
import cdac.medinfo.sdk.hl7282.hl7net.commons.IHL7BatchFile;
import cdac.medinfo.sdk.hl7282.hl7net.commons.ITransactionHandler;
import cdac.medinfo.sdk.hl7282.hl7net.upperlayer.IBatchReceiver;
import cdac.medinfo.sdk.hl7282.hl7net.upperlayer.UserSession;
import cdac.medinfo.sdk.hl7282.utils.EnumMessageCode;
import cdac.medinfo.sdk.hl7282.utils.EnumMessageStructure;
import cdac.medinfo.sdk.hl7282.utils.EnumSegments;
import cdac.medinfo.sdk.hl7282.utils.HL7Config;
import cdac.medinfo.sdk.hl7282.utils.HL7Logger;
import cdac.medinfo.sdk.hl7282.utils.IMap;
import cdac.medinfo.sdk.hl7282.utils.IMessageMapReader;
import cdac.medinfo.sdk.hl7282.utils.SingleCollection;
import cdac.medinfo.sdk.hl7282.utils.StandardMethods;

/**
 * This class acts as main class for Client Utility tool of HL7.
 * It initializes the Sever Class for required parameters.
 */
public class HL7Client 
{
	static int lengthOfOption = 18;
	static int lengthOfDetails = 80 - lengthOfOption;

	public static void main(String args[])
	{
		String strLoggingPath = null;
		int iPort = 0;
		String strIP = null;
		String strDestinationPath = null,strFilePath = null;
		int iWaitPeriod = 8000;
		int iTimeOutPeriod = -1;
		ISingleCollection<String> objFilePathCollection = new SingleCollection<String>();
		ISingleCollection<String> objBatchPathCollection = new SingleCollection<String>();
		HL7Client objClientTool = new HL7Client();


		String strIniFile = null;
		String strKey = null;
		/*
		 * If no parameters are provided then help need to be displayed.
		 */
		if(args == null || args.length ==0)
		{
			objClientTool.displayHelp();
			System.exit(0);
		}
		/*
		 * Checks the command line arguments and its repeatabilty 
		 * Allowed same type of message to send i.e Message or batch or batchfile
		 * Mixed combination of message not allowed.
		 * Repeatabilty of same command gives warning message and exits. 
		 */
		for(int i=0; i<args.length;i=i+2)
		{
			for(int j=i+2;j<args.length;j=j+2)
			{
				if(args[i].equalsIgnoreCase(args[j]))
				{		
					if(!(args[i].equalsIgnoreCase("-m")||args[i].equalsIgnoreCase("-b")))
					{
						System.out.println("Not a valid Multiple Occurences "+args[i]);
						System.exit(0);
					}
				}
			}
		}

		/*
		 * Initializing required parameters provided through cmd line arguments.
		 */
		for(int i=0; i<args.length; i++)
		{
			if(args[i].equalsIgnoreCase("-d") && args.length > i+1)
			{
				//Reading logging path information
				strLoggingPath = args[i+1];
				i++;
			}
			
			else if(args[i].equalsIgnoreCase("-p") && args.length > i+1)
			{
				//reading port information
				String strPort = args[i+1];
				iPort = Integer.parseInt(strPort);
				if(iPort == 0)
				{
					System.out.println("Not a valid command");
					System.exit(0);
				}
				i++;
			}
			else if(args[i].equalsIgnoreCase("-i") && args.length > i+1)
			{
				//reading IP address information
				strIP = args[i+1];
				i++;
			}
			else if(args[i].equalsIgnoreCase("-s") && args.length > i+1)
			{
				//reading destination dir path where received requests will be dumped
				strDestinationPath = args[i+1] ;
				i++;
			}
			else if(args[i].equalsIgnoreCase("-m")&& args.length > i+1)
			{
				//reading file path for HL7 message
				strFilePath = args[i+1] ;
				objFilePathCollection.add(strFilePath);
				i++;
			}
			else if(args[i].equalsIgnoreCase("-b")&& args.length > i+1)
			{
				//reading file path for HL7 batch
				strFilePath = args[i+1] ;
				objBatchPathCollection.add(strFilePath);
				i++;
			}
			else if(args[i].equalsIgnoreCase("-w") && args.length > i+1)
			{
				//reading value wait period after which resending of request will be performed
				String strWP = args[i+1];
				int iWP = Integer.parseInt(strWP);
				if(iWP != 0)
				{
					iWaitPeriod = iWP;
				}
				i++;
			}
			else if(args[i].equalsIgnoreCase("-t") && args.length > i+1)
			{
				//reading value of No. of attempts for which resending will be done
				String strTimeOutPeriod = args[i+1];
				int iTimeOut = Integer.parseInt(strTimeOutPeriod);
				if(iTimeOut != 0)
				{
					iTimeOutPeriod = iTimeOut;
				}
				i++;
			}
			else
			{
				System.out.println("Not a valid command");
				objClientTool.displayHelp();
				System.exit(0);
			}


		}

		//server IP/port  address and request file are minimum parameters to run the client
		if(iPort ==0 ||strFilePath == null)
		{
			System.out.println("Not a valid command");
			objClientTool.displayHelp();
			System.exit(0);
		}

		HISClient objHISClient = new HISClient();
		objHISClient.setINIFile(strIniFile);
		objHISClient.setKey(strKey);
		objHISClient.initiate(strLoggingPath,strIP,iPort,strDestinationPath,iWaitPeriod,objFilePathCollection,objBatchPathCollection,iTimeOutPeriod);
	}

	/*
	 * This function displays the help.
	 */
	private void displayHelp()
	{
		//Description of command
		System.out.println("\nHL7CLIENT :: Sends HL7 supported message, batch and batchfiles.");

		//Signature
		System.out.println("\n" + "HL7CLIENT [-i IP] -p Port [-d LogDir]  " +
				"[-s StorageDir] \n {-m FileName} {-b FileName} [-w WaitPeriod] " +
				"[-t TimeOut] \n  " + "\n");

		//IP Address
		printToConsole("-i", "IP Address, default IP address is localhost.");

		//Port
		printToConsole("-p", "Port");

		//Log directory
		printToConsole("-d", "Log directory");
		printToConsole("", "User's temp directory is taken as default.");


		//Storage directory
		printToConsole("-s","Destination folder to store the received ACK and Batch files");
		printToConsole("", "User's temp directory is taken as default.");

		//HL7 Message
		printToConsole("-m","Absolute path of file containing HL7 message data");

		//BL7 Batch
		printToConsole("-b","Absolute path of file containing HL7 batch or batchfile data");

		//Wait Period
		printToConsole("-w","Time period after which request will be resend if response is");
		printToConsole("", "not received");

		//Session time out
		printToConsole("-t","Session time out in milliseconds");
		
        
        System.out.println("\nExample :");

		//Example and its description
		System.out.println("\n1. HL7CLIENT -p 9999 -m 01_ADT_Event.HL7" +
				"\nSends HL7 message to HL7 server running on localhost and " +
		"listening on port 9999.");

		//		Example and its description
		System.out.println("\n2. HL7CLIENT -p 9999 -b ADT_A01_Batch.hl7" +
				"\nSends HL7 batch to HL7 server running on localhost and " +
		"listening on port 9999.");

		//		Example and its description
		System.out.println("\n3. HL7CLIENT -p 9999 -b ADT_A01_BatchFile.hl7" +
				"\nSends HL7 batch file to HL7 server running on localhost and " +
		"listening on port \n9999.");

	}

	/**
	 * Display Help of command on console in proper manner.
	 * @param strOption Option for command.
	 * @param strDetails Description of option.
	 */
	public static void printToConsole(String strOption, String strDetails)
	{
		String strBuffer = "";
		if (strOption != null)
			strBuffer = strBuffer + strOption ;
		while (lengthOfOption > strBuffer.length())
		{
			strBuffer = strBuffer + " ";
		}
		if (strDetails != null)
		{
			if (strDetails.length() < lengthOfDetails || strDetails.length() == lengthOfDetails)
			{
				strBuffer = strBuffer + strDetails;
				strDetails = null;
			}
			else
			{
				strBuffer = strBuffer + strDetails.substring(0, lengthOfDetails);
				strDetails = strDetails.substring(lengthOfDetails, (strDetails.length() ));
			}
		}

		System.out.println(strBuffer);
		if (strDetails == null)
			return;
		else
			printToConsole(null, strDetails);
	}

	/**
	 * Display Help of command on console in proper manner.
	 * @param strAttribute Attribute for option.
	 * @param strDesc Description of attributes.
	 */
	public static void printToConsole(String strAttribute, String[] strDesc)
	{
		if (strDesc.length > 1)
			printToConsole(strAttribute, strDesc[0]);
		for(int i = 1;i<strDesc.length;i++)
			printToConsole(null, strDesc[i]);
	}
}

/**
 * This sample code demonstrates implementation of Health Information System.
 * This System works as a client for different HL7 systems. 
 * It specifies the request process for an event of different systems.
 * It also support requests using batch or batch file of events.
 */
class HISClient implements IBatchReceiver
{
	UserSession objUserSession = null;
	MessageFactory objMsgFactory = null;
	IBatchProcessor objIBatchProcessor = null;
	ITransactionHandler objTransactionHandler = null;
	ISingleCollection<String> objFilePathCollection = null;
	ISingleCollection<String> objBatchPathCollection = null;
	ISingleCollection<String> objBatchFilePathCollection = null;
	int iWaitPeriod,iTimeOutPeriod;
	String strDestinationPath;

	//	private final String HL7Batch_QualifiedName = "cdac.medinfo.sdk.hl725.hl7net.auxiliaryprotocol.batch.HL7Batch";
	//	private final String HL7BatchFile_QualifiedName = "cdac.medinfo.sdk.hl725.hl7net.auxiliaryprotocol.batch.HL7BatchFile";


	private String strIniFile;
	private String strKey;

	public void setINIFile(String strIniFile)
	{
		this.strIniFile = strIniFile;
	}
	public void setKey(String strKey)
	{
		this.strKey = strKey;
	}

	public String getINIFile()
	{
		return this.strIniFile;
	}
	public String getKey()
	{
		return this.strKey;
	}


	/**
	 * Initiates this System as a Client for different HL7 systems. 
	 * Connects the Client to Server on specific IP Address & port on which Server System is listening.
	 * @param strIP  IP Address specified
	 * @param port port specified 
	 */
	public void initiate(String strLoggingPath,String strIP,int port,String strDestPath,int iWP,ISingleCollection<String> objFilePathCollection,ISingleCollection<String> objBatchPathCollection,int iTimeoutPeriod)
	{
		try 
		{
			HL7Config objHL7Config = HL7Config.createInstance();

			//Specifying logging directory.
			//User can specify any directory where log files will be created.
			//If no path is specified then logs will be generated in user's temp directory. 
			objHL7Config.enableLogging(strLoggingPath);

			
			this.objFilePathCollection = objFilePathCollection;
			this.iWaitPeriod = iWP;
			this.strDestinationPath = strDestPath;
			this.iTimeOutPeriod = iTimeoutPeriod;

			//Creating user session for Client
			objUserSession  = new UserSession();

			/*
			 * Initializing source for different systems and adding them on user session. 
			 * By setting source on user sesson, client becomes capable to create messages and receive responses of specific System
			 */
			objMsgFactory = MessageFactory.createInstance();
			IMessageRecepient objADTRecepient  = new ADTRecepient();
			objMsgFactory.addMessageRecepient(objADTRecepient);

			IMessageSource objADTSource = new ADTSource();
			objMsgFactory.addMessageSource(objADTSource);

			IMessageRecepient objFinancialRecepient = new FinancialRecepient();
			objMsgFactory.addMessageRecepient(objFinancialRecepient);

			IMessageRecepient objPatientCareRecepient = new PatientCareRecepient();
			objMsgFactory.addMessageRecepient(objPatientCareRecepient);

			IMessageRecepient objPatientRefRecepient = new PatientRefRecepient();
			objMsgFactory.addMessageRecepient(objPatientRefRecepient);

			IMessageRecepient objClinicalLabAutoRecepient = new ClinicalLabAutoRecepient();
			objMsgFactory.addMessageRecepient(objClinicalLabAutoRecepient);

			IMessageRecepient objSchedulingRecepient = new SchedulingRecepient();
			objMsgFactory.addMessageRecepient(objSchedulingRecepient);

			IMessageRecepient objAppMgtRecepient = new AppMgtRecepient();
			objMsgFactory.addMessageRecepient(objAppMgtRecepient);

			IMessageRecepient objMasterFileRecepient = new MasterFileRecepient();
			objMsgFactory.addMessageRecepient(objMasterFileRecepient);

			IMessageRecepient objMediRecRecepient = new MediRecRecepient();
			objMsgFactory.addMessageRecepient(objMediRecRecepient);

			IMessageRecepient objObsvRepRecepient = new ObsvRepRecepient();
			objMsgFactory.addMessageRecepient(objObsvRepRecepient);

			IMessageRecepient objOrderEntryRecepient = new OrderEntryRecepient();
			objMsgFactory.addMessageRecepient(objOrderEntryRecepient);

			IMessageRecepient objPersonalMgmtRecepient = new PersonalMgmtRecepient();
			objMsgFactory.addMessageRecepient(objPersonalMgmtRecepient);


			objUserSession.setMessageFactory(objMsgFactory);

			objUserSession.setIBatchReceiver(this);

			/*
			 * Instantiating IFragmentProcessor which handles the fragmentaion and defragmention for larger messages.
			 * FragmentAgent is the default implementation provided by sdk for HL7.
			 * User can provide his own implementaion for FragmentProcessor by implementing IFragmentProcessor interface.
			 */ 
			IFragmentProcessor objIFragmentProcessor = new FragmentAgent();

			//Setting Fragment processor on user session.
			objUserSession.setFragmentProcessor(objIFragmentProcessor);

			/*
			 * Instantiating IBatchProcessor which handles HL7Batch and HL7BatchFiles.
			 * BatchAgent is the default implementation provided by sdk for HL7.
			 * User can provide his own implementaion for BatchProcessor by implementing IBatchProcessor interface.
			 */
			objIBatchProcessor = new BatchAgent();

			//Setting Batch Processor on user session
			objUserSession.setBatchProcessor(objIBatchProcessor);

			//Set the reading and writing max length for this client which will be used to decide whehther to fragment or not.
			objUserSession.setReadWriteLength(1024,1024);

			//Setting time period for which usersession will read on socket 
			//for given time period in milliseconds. 
			//The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.
			if(iTimeOutPeriod > 0)
				objUserSession.setTimeOut(iTimeOutPeriod);

			//Setting time for which user Session should wait for ACK/Response to arrive from remote end.
			//If time frame is elapsed then user session resends Event/Query message.
			//objUserSession.setWaitPeriod(iWaitPeriod);

			//Setting TransactionHandler.
			objTransactionHandler = new TransactionHandler();
			
			//Setting this transaction handler on User session.
			objUserSession.setClientSideTransactionHandler(objTransactionHandler);


			//If IP address is not given then by default it will be LocalHost
			if(strIP==null)
			{
				InetAddress ownIP = InetAddress.getLocalHost();
				strIP= ownIP.getHostAddress();
			}
			//Connecting this client with Server
			objUserSession.connect(strIP, port);

			System.out.println("Connection Established");

			if(objFilePathCollection != null)
			{
				for(String strpath : objFilePathCollection)
				{
					if(objUserSession.sendMessage(strpath))
					{
						ISingleCollection<Message> ackCollection = objUserSession.getRecievedMessagesCollection((String)getMessageFromPath(strpath).getHeader().getMessageControlID().getValue());
						if(ackCollection != null)
						{
							for(Message objMessage : ackCollection)
							{
								ACK ackMessage =(ACK)objMessage;
								System.out.println("ACK Received for event :: " + ackMessage.getTriggerEvent());
								dumpMessage(ackMessage);
							}
						}
						else
							System.out.println("ACK Collection is empty");
					}
					else
					{
						System.out.println("HL7 Message Processing Failed ..... Check log file");
					}
				}
			}
			if(objBatchPathCollection != null)
			{
				for(String strpath : objBatchPathCollection)
				{
					if(objUserSession.sendBatchFile(strpath))
					{
						System.out.println("HL7 Batch Processed Successfully");
					}
					else
					{
						System.out.println("HL7 Batch Processing Failed ..... Check log file");
					}
				}
			}
			objUserSession.close();

		}
		catch (Exception e)
		{
			System.out.println("Error Occured in Processing "+ e.getMessage());
			e.printStackTrace();
			if(HL7Config.createInstance().isLoggingOn())
			{
				HL7Logger objHLogger = HL7Logger.getLogger();
				objHLogger.log(e);
			}
			try
			{
				objUserSession.close();
			} catch (IOException e1) 
			{
				e1.printStackTrace();
				if(HL7Config.createInstance().isLoggingOn())
				{
					HL7Logger objHLogger = HL7Logger.getLogger();
					objHLogger.log(e1);
				}
			}
		}
	}



	/**
	 * This method will be invoked when Batch response is received from remote system.
	 * User provides the implementation of this method.
	 * Simulation of user code is demonstrated below.
	 * @param objRSPBatchFile instance of response BatchFile
	 */
	@Override
	public void onBatchReceive(IHL7BatchFile objRSPBatchFile) 
	{
		ISingleCollection<IHL7Batch> objACKBatchCollection = objRSPBatchFile.getHL7BatchCollection();
		if (objACKBatchCollection != null)
		{
			for(IHL7Batch objBatch : objACKBatchCollection)
			{
				System.out.println("ACK Received for Batch :: " + objBatch.getBatchControlID() + "\n");
				dumpMessage(objRSPBatchFile);
			}
		}
		else
			System.out.println("ACK Collection is empty");
	}




	/**
	 * This method simulates user action to generate Acknowledgement from message received.
	 * This method is demonstrated for test purpose only.
	 * In the actual scenerion,it is the responsibility of user to generates acknowledgement & sends it on remote end. 
	 * @param objReceivedMessage specified Message object
	 * @return ACK message object
	 */
	public ACK generateAcknowledgement(Message objReceivedMessage)
	{
		IMessageMapReader objMessageMapReader = MessageMapReader.createInstance();
		IMap objMessageMap = objMessageMapReader.getMessageMap(EnumMessageCode.ACK, null);

		ACK ackMessage = new ACK(StandardMethods.getEnumTriggerEvent(objReceivedMessage.getTriggerEvent()), objMessageMap);
		MSH objNewMSH = objReceivedMessage.getHeader();
		objNewMSH.setMessageType(EnumMessageCode.ACK.getValue(), objReceivedMessage.getTriggerEvent(), EnumMessageStructure.ACK.getValue());
		ackMessage.setHeader(objNewMSH);
		//MSA Segment
		MSA objMSA = new MSA();
		objMSA.setAcknowledgmentCode("AA");
		objMSA.setMessageControlID((String)objReceivedMessage.getHeader().getMessageControlID().getValue());
		objMSA.setExpectedSequenceNumber("1234567");
		ackMessage.setMessageAcknowledgmentSegment(objMSA);
		return ackMessage;
	}

	/**
	 * This method is invoked when exception is fetched from remote end.
	 * @ex Exception fetched
	 * @buffer for which exception is received</param>
	 */

	public void onException(Exception ex,byte[] buffer) 
	{
		System.out.println("Exception Occured While Processing");
		System.out.println(ex.getMessage());
		try
		{
			System.out.println("Errorneous Buffer :: ");
			ByteArrayOutputStream objByteArrayOutputStream = new ByteArrayOutputStream();
			objByteArrayOutputStream.write(buffer);
			objByteArrayOutputStream.writeTo(System.out);
			objByteArrayOutputStream.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	private boolean dumpMessage(Message objMessage)
	{
		try
		{
			String strDestFilePath = null;

			if(strDestinationPath != null)
			{
				if(!strDestinationPath.endsWith(File.separator))
					strDestinationPath = strDestinationPath + File.separator;

				File objFile = new File(strDestinationPath);
				objFile.mkdirs();
				strDestFilePath = strDestinationPath + StandardMethods.generateUUID() + ".HL7";
			}
			else
			{
				String strLogLocation = StandardMethods.getTempDirectoryStorage() + "CDAC-SDK/HL7-J/Dump";
				File objFile = new File(strLogLocation);
				if(!objFile.exists())
					objFile.mkdirs();
				strDestFilePath = objFile.getPath() + File.separator + StandardMethods.generateUUID() + ".HL7";
			}

			HL7Serializer objHL7Serializer = new HL7Serializer();
			objHL7Serializer.serialize(objMessage.getSegmentSet(),strDestFilePath);

			return true;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return false;
	}

	private boolean dumpMessage(IHL7BatchFile objIHL7BatchFile)
	{
		try
		{
			String strDestFilePath = null;

			if(strDestinationPath != null)
			{
				if(!strDestinationPath.endsWith(File.separator))
					strDestinationPath = strDestinationPath + File.separator;

				File objFile = new File(strDestinationPath);
				objFile.mkdirs();
				strDestFilePath = strDestinationPath + StandardMethods.generateUUID() + ".HL7";
			}
			else
			{
				String strLogLocation = StandardMethods.getTempDirectoryStorage() + "CDAC-SDK/HL7-J/Dump";
				File objFile = new File(strLogLocation);
				if(!objFile.exists())
					objFile.mkdirs();
				strDestFilePath = objFile.getPath() + File.separator + StandardMethods.generateUUID() + ".HL7";
			}

			ISegmentSet objSegmentSet = objIBatchProcessor.getSegmentSet(objIHL7BatchFile);
			HL7Serializer objHl7Serializer = new HL7Serializer();
			objHl7Serializer.serialize(objSegmentSet, strDestFilePath);

			return true;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return false;
	}

	public Message getMessageFromPath(String strFilepath)
	{
		try 
		{
			HL7Parser objHL7Parser = new HL7Parser();
			ISegmentSet objSegmentSet = objHL7Parser.parse(strFilepath);

			String strMsgCode =null;
			String strTrgEvent = null;
			Segment objTempSegment = (Segment)objSegmentSet.getSegment(0);
			if(objTempSegment.getName().equals(EnumSegments.HL7_SEG_MSH))
			{
				MSH objMSH = (MSH)objTempSegment;
				strMsgCode = (String)objMSH.getMessageType().getMessageCode().getValue();
				strTrgEvent = (String)objMSH.getMessageType().getTriggerEvent().getValue();
			}
			
			Message objMessage = objMsgFactory.createSendSupportedMessage(strMsgCode, strTrgEvent);

			if(objMessage != null)
				objMessage.populate(objSegmentSet);

			return objMessage;
		}
		catch(MessageNotSupportedException mse)
		{
			if(HL7Config.createInstance().isLoggingOn())
			{
				HL7Logger objHL7Logger = HL7Logger.getLogger();
				objHL7Logger.log(mse);
			}
		}
		catch (Exception e) 
		{
			if(HL7Config.createInstance().isLoggingOn())
			{
				HL7Logger objHL7Logger = HL7Logger.getLogger();
				objHL7Logger.log(e);
			}
		}
		return null;
	}

	public IHL7BatchFile getBatchFromPath(String strFilePath)
	{
		try
		{
			HL7Parser objHL7Parser = new HL7Parser();
			ISegmentSet objSegmentSet = objHL7Parser.parse(strFilePath);

			IHL7BatchFile objBatchFile = objIBatchProcessor.processReceive(objMsgFactory,objSegmentSet);

			return objBatchFile;
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
		return null;
	}
}
