package cdac.medinfo.sdk.hl7282.HL7Dump;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

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.segments.MSH;
import cdac.medinfo.sdk.hl7282.commoninterface.ISegment;
import cdac.medinfo.sdk.hl7282.commoninterface.ISegmentSet;
import cdac.medinfo.sdk.hl7282.commoninterface.ISingleCollection;
import cdac.medinfo.sdk.hl7282.hl7model.messages.applicationmanagement.AppMgtRecepient;
import cdac.medinfo.sdk.hl7282.hl7model.messages.applicationmanagement.AppMgtSource;
import cdac.medinfo.sdk.hl7282.hl7model.messages.clinicallaboratoryautomation.ClinicalLabAutoRecepient;
import cdac.medinfo.sdk.hl7282.hl7model.messages.clinicallaboratoryautomation.ClinicalLabAutoSource;
import cdac.medinfo.sdk.hl7282.hl7model.messages.financialmanagement.FinancialRecepient;
import cdac.medinfo.sdk.hl7282.hl7model.messages.financialmanagement.FinancialSource;
import cdac.medinfo.sdk.hl7282.hl7model.messages.masterfiles.MasterFileRecepient;
import cdac.medinfo.sdk.hl7282.hl7model.messages.masterfiles.MasterFileSource;
import cdac.medinfo.sdk.hl7282.hl7model.messages.medicalrecords.MediRecRecepient;
import cdac.medinfo.sdk.hl7282.hl7model.messages.medicalrecords.MediRecSource;
import cdac.medinfo.sdk.hl7282.hl7model.messages.observationreporting.ObsvRepRecepient;
import cdac.medinfo.sdk.hl7282.hl7model.messages.observationreporting.ObsvRepSource;
import cdac.medinfo.sdk.hl7282.hl7model.messages.orderentry.OrderEntryRecepient;
import cdac.medinfo.sdk.hl7282.hl7model.messages.orderentry.OrderEntrySource;
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.patientcare.PatientCareSource;
import cdac.medinfo.sdk.hl7282.hl7model.messages.patientreferral.PatientRefRecepient;
import cdac.medinfo.sdk.hl7282.hl7model.messages.patientreferral.PatientRefSource;
import cdac.medinfo.sdk.hl7282.hl7model.messages.personnelmanagement.PersonalMgmtRecepient;
import cdac.medinfo.sdk.hl7282.hl7model.messages.personnelmanagement.PersonalMgmtSource;
import cdac.medinfo.sdk.hl7282.hl7model.messages.query.QryRecepient;
import cdac.medinfo.sdk.hl7282.hl7model.messages.query.QrySource;
import cdac.medinfo.sdk.hl7282.hl7model.messages.scheduling.SchedulingRecepient;
import cdac.medinfo.sdk.hl7282.hl7model.messages.scheduling.SchedulingSource;
import cdac.medinfo.sdk.hl7282.hl7streams.HL7FileStream;
import cdac.medinfo.sdk.hl7282.unrecognized.UnRecognizedField;
import cdac.medinfo.sdk.hl7282.unrecognized.UnRecognizedSegment;
import cdac.medinfo.sdk.hl7282.utils.EnumSegments;
import cdac.medinfo.sdk.hl7282.utils.HL7Config;


/**
 * This test code will dump information of message like its segments, groups and its attribute values to MS document.
 */
public class HL7Dump 
{
	private HL7FileStream objIHL7Stream;

	public static void main(String[] args) 
	{
		HL7Dump objHL7Dump = new HL7Dump();
		
		try
		{
			//User define HL7 file
			System.out.println("Enter HL7 file to dump:   ");
			
			InputStreamReader input = new InputStreamReader(System.in);
			BufferedReader reader = new BufferedReader(input);
			
			String strHL7File = reader.readLine();
			
			//User can define its own destination folder
			//where user can dump HL7 file			
			System.out.println("Enter destination folder where to dump HL7 file:   ");


			String strDestFolder = reader.readLine();

			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(null);
			
			if(strHL7File != null)
			{
				if(strDestFolder == null || strDestFolder.equalsIgnoreCase(""))
					objHL7Dump.dumpHL7Message(strHL7File, strDestFolder);
				else
					objHL7Dump.dumpHL7Message(strHL7File, strDestFolder);
			}
			else
			{			
				System.out.println("Not a valid command, Source HL7 file for dump is not specified.");
			}
		}
		catch(FileNotFoundException exception)
		{
			System.out.println("Operation failed :" + exception.getMessage());
		}
		catch(Exception exception)
		{
			System.out.println("Operation failed :" + exception.getMessage());
		}
	}

	/**
	 * Creates the MS document for HL7 file.
	 * @param strHL7File HL7 File path.
	 * @param strDestinationPath  Destination folder to store created document.
	 */
	private void dumpHL7Message(String strHL7File,String strDestinationPath) throws Exception
	{
		
		/* 
		 * The HL7Parser parses the HL7Message and provides a SegmentSet.
		 * SegmentSet contains all segments of a HL7 Message in the same order as they appeared.
		 */
		HL7Parser objParser = new HL7Parser();
		ISegmentSet objSegmentSet = objParser.parse(strHL7File);

		ISegment objSegment = objSegmentSet.getSegment(0);
		String strSegment = objSegment.getName().getValue();
		strSegment = strSegment.trim();

		if(strSegment.equals(EnumSegments.HL7_SEG_MSH.getValue()))
		{
			//Retrieve TriggerEvent and MessageCode
			MSH objMSH = (MSH)objSegment; 
			String strTriggerEvent = (String)objMSH.getMessageType().getTriggerEvent().getValue();
			String strMessageCode = (String)objMSH.getMessageType().getMessageCode().getValue();

			Message objMessage = getMessage(strMessageCode, strTriggerEvent, objSegmentSet);
			
			//Create Dump folder and file
			getFileForDump(strTriggerEvent,strMessageCode,strDestinationPath);

			//Call Dump
			if(objMessage != null)
				objMessage.dumpMessage(objIHL7Stream);

			System.out.println("\nDump of HL7 message is stored at " + strDestinationPath);
		}
		else
		{
			System.out.println("\nOperation supported for HL7 messages only. ");
		}
		
		//To display UnrecognizedSegment
		if(objSegmentSet.getUnRecognizedSegments()!= null && objSegmentSet.getUnRecognizedSegments().size()>0)
		{
			displayUnrecognizedSegment(objSegmentSet.getUnRecognizedSegments());
		}
		int i=0;
		
		//To display UnrecognizedFields
		while(i<objSegmentSet.size())
		{
			ISegment objSeg = objSegmentSet.getSegment(i);
			if(objSeg.getUnrecognizedFields()!=null && objSeg.getUnrecognizedFields().size()>0)
			{
				displayUnrecognizedField(objSeg.getUnrecognizedFields());
			}
			i++;
		}
	}

	/**
	 * Display all the Unrecognized Segment and its value.
	 * @param objUnRecognizedSegment Collection of UnrecognizedSegment
	 */
	private void displayUnrecognizedSegment(ISingleCollection<UnRecognizedSegment> objUnRecognizedSegment)
	{
		System.out.println("Unrecognized Segment");
		for (UnRecognizedSegment unrecognizedSegment : objUnRecognizedSegment) {
			System.out.println("Segment : "+unrecognizedSegment.getName()+" value : "+unrecognizedSegment.getUnRecognizedData());
		}
	}
	
	/**
	 * Display all the Unrecognized Field along with the name of the Segment in which it belong.
	 * @param objUnRecognizedField Collection of UnrecognizedField.
	 */
	private void displayUnrecognizedField(ISingleCollection<UnRecognizedField> objUnRecognizedField)
	{
		
		for (UnRecognizedField unRecognizedField : objUnRecognizedField) {
			System.out.println("Segment : "+unRecognizedField.getSegmentName()+" Field : "+unRecognizedField.getFieldName()+" value : "+unRecognizedField.getUnRecognizedData());
		}
	}
	
	/*
	 * Populates message through provided SegmentSet,MessageCode and TriggerEvent
	 */
	private Message getMessage(String strMessageCode,String strTriggerEvent,ISegmentSet objSegmentSet)
	{
		Message objMessage = null;

		MessageFactory objMessageFactory = getMessageFactory();

		objMessage = objMessageFactory.populateReceiveSupportedMessage(strMessageCode, strTriggerEvent, objSegmentSet);

		if(objMessage != null)
		{
			objMessage = objMessageFactory.createSendSupportedMessage(strMessageCode, strTriggerEvent);
			if(objMessage != null)
				objMessage.populate(objSegmentSet);
		}

		return objMessage;
	}

	/*
	 * Populates Message Factory
	 */
	private MessageFactory getMessageFactory()
	{
		MessageFactory objMessageFactory = MessageFactory.createInstance();

		objMessageFactory.addMessageSource(new ObsvRepSource());
		objMessageFactory.addMessageRecepient(new ObsvRepRecepient());
		objMessageFactory.addMessageSource(new AppMgtSource());
		objMessageFactory.addMessageRecepient(new AppMgtRecepient());
		objMessageFactory.addMessageSource(new ClinicalLabAutoSource());
		objMessageFactory.addMessageRecepient(new ClinicalLabAutoRecepient());
		objMessageFactory.addMessageSource(new FinancialSource());
		objMessageFactory.addMessageRecepient(new FinancialRecepient());
		objMessageFactory.addMessageSource(new MasterFileSource());
		objMessageFactory.addMessageRecepient(new MasterFileRecepient());
		objMessageFactory.addMessageSource(new MediRecSource());
		objMessageFactory.addMessageRecepient(new MediRecRecepient());
		objMessageFactory.addMessageSource(new OrderEntrySource());
		objMessageFactory.addMessageRecepient(new OrderEntryRecepient());
		objMessageFactory.addMessageSource(new ADTSource());
		objMessageFactory.addMessageRecepient(new ADTRecepient());
		objMessageFactory.addMessageSource(new PatientCareSource());
		objMessageFactory.addMessageRecepient(new PatientCareRecepient());
		objMessageFactory.addMessageSource(new PatientRefSource());
		objMessageFactory.addMessageRecepient(new PatientRefRecepient());
		objMessageFactory.addMessageSource(new PersonalMgmtSource());
		objMessageFactory.addMessageRecepient(new PersonalMgmtRecepient());
		objMessageFactory.addMessageSource(new QrySource());
		objMessageFactory.addMessageRecepient(new QryRecepient());
		objMessageFactory.addMessageSource(new SchedulingSource());
		objMessageFactory.addMessageRecepient(new SchedulingRecepient());

		return objMessageFactory;
	}

	/**
	 * Generates file for dumping.
	 * @param strTriggerEvent String value for TriggerEvent
	 * @param strMessageCode String value for MessageCode
	 * @param strDestinationPath String value Destination Dolder Path
	 */
	private void getFileForDump(String strTriggerEvent,String strMessageCode, String strDestinationPath)
	{
		File objFileWrite;
		FileOutputStream objFileOutputStream;
		
		objIHL7Stream = new HL7FileStream();
		try
		{
			File testDir =  new File(strDestinationPath);
			testDir.mkdir();
			String strPathForDump = null;
			strPathForDump = strDestinationPath + "\\" +  strMessageCode+"_"+strTriggerEvent+".doc";
			objFileWrite = new File(strPathForDump);
			objFileWrite.createNewFile();
			objFileOutputStream = new FileOutputStream(objFileWrite);	
			objIHL7Stream.setOutputStream(objFileOutputStream);
		}
		catch(IOException ioe)
		{
			ioe.printStackTrace();
		}
	}
}
