/*******************************************************************************
 *  Copyright 2017-2018 Centre for Development of Advanced Computing(C-DAC), Pune
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *   http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package cdac.medinfo.sdk.dcm30_04.services.appeventlogging.testcases.scu;

import cdac.medinfo.sdk.dcm30_04.baselibs.DicomV3Factory;
import cdac.medinfo.sdk.dcm30_04.baselibs.ImagePixelMacro;
import cdac.medinfo.sdk.dcm30_04.baselibs.ImplicitDE;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IDataElement;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IDataSet;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IDataTypeSQ;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IDictionaryReader;
import cdac.medinfo.sdk.dcm30_04.commoninterface.ITransferSyntax;
import cdac.medinfo.sdk.dcm30_04.dicommodel.modules.SRDocumentContentModule;
import cdac.medinfo.sdk.dcm30_04.dicommodel.sr.ProcedureLogIOD;
import cdac.medinfo.sdk.dcm30_04.enums.EnumContinuityOfContent;
import cdac.medinfo.sdk.dcm30_04.enums.EnumGraphicType;
import cdac.medinfo.sdk.dcm30_04.enums.EnumLoggingLevel;
import cdac.medinfo.sdk.dcm30_04.enums.EnumPDUType;
import cdac.medinfo.sdk.dcm30_04.enums.EnumRelationshipType;
import cdac.medinfo.sdk.dcm30_04.enums.EnumSOPClassUIDs;
import cdac.medinfo.sdk.dcm30_04.enums.EnumTemporalRangeType;
import cdac.medinfo.sdk.dcm30_04.services.ael.scu.AEL_SCU;
import cdac.medinfo.sdk.dcm30_04.services.association.AAbort;
import cdac.medinfo.sdk.dcm30_04.services.association.AReleaseRQorRP;
import cdac.medinfo.sdk.dcm30_04.services.association.AssociateRQ;
import cdac.medinfo.sdk.dcm30_04.services.association.DefaultAssociation;
import cdac.medinfo.sdk.dcm30_04.services.dicomnetcommons.EnumActionTypeID;
import cdac.medinfo.sdk.dcm30_04.services.dicomnetcommons.EnumServiceType;
import cdac.medinfo.sdk.dcm30_04.services.naction.commons.NActionRQ;
import cdac.medinfo.sdk.dcm30_04.services.naction.commons.NActionRSP;
import cdac.medinfo.sdk.dcm30_04.services.scu.commons.SCUSession;
import cdac.medinfo.sdk.dcm30_04.srtree.SRDocument;
import cdac.medinfo.sdk.dcm30_04.srtree.SRNode;
import cdac.medinfo.sdk.dcm30_04.srtree.SRTree;
import cdac.medinfo.sdk.dcm30_04.templates.enums.cm.EnumCM_AcquisitionModality;
import cdac.medinfo.sdk.dcm30_04.templates.enums.cm.EnumCM_ActionsWithConsumables;
import cdac.medinfo.sdk.dcm30_04.templates.enums.cm.EnumCM_ArterialSourceLocations;
import cdac.medinfo.sdk.dcm30_04.templates.enums.cm.EnumCM_CIDProcedureAction;
import cdac.medinfo.sdk.dcm30_04.templates.enums.cm.EnumCM_DateTimeQualifiers;
import cdac.medinfo.sdk.dcm30_04.templates.enums.cm.EnumCM_DeviceUseActions;
import cdac.medinfo.sdk.dcm30_04.templates.enums.cm.EnumCM_GradientSourceLocations;
import cdac.medinfo.sdk.dcm30_04.templates.enums.cm.EnumCM_InterventionActionsAndStatus;
import cdac.medinfo.sdk.dcm30_04.templates.enums.cm.EnumCM_NumericParametersOfDrugsContrast;
import cdac.medinfo.sdk.dcm30_04.templates.enums.cm.EnumCM_ObserverType;
import cdac.medinfo.sdk.dcm30_04.templates.enums.cm.EnumCM_OrganizationalRoles;
import cdac.medinfo.sdk.dcm30_04.templates.enums.cm.EnumCM_PatientStatusAndEvents;
import cdac.medinfo.sdk.dcm30_04.templates.enums.cm.EnumCM_PerformingRole;
import cdac.medinfo.sdk.dcm30_04.templates.enums.cm.EnumCM_ProcedureActionValues;
import cdac.medinfo.sdk.dcm30_04.templates.enums.cm.EnumCM_ProcedureLogTitles;
import cdac.medinfo.sdk.dcm30_04.templates.enums.cm.EnumCM_RouteOfAdministration;
import cdac.medinfo.sdk.dcm30_04.templates.enums.cm.EnumCM_StaffAction;
import cdac.medinfo.sdk.dcm30_04.templates.enums.cm.EnumCM_TypesOfLogNotes;
import cdac.medinfo.sdk.dcm30_04.templates.procedurelogiodtemplates.ProcedureLog_TID3001;
import cdac.medinfo.sdk.dcm30_04.utils.DicomConfig;
import cdac.medinfo.sdk.dcm30_04.utils.DicomConstants;

/**
 * This class is implemented to test the AEL SCU.
 * The Application Event Logging Service Class defines an application-level class-of-service that
 * facilitates the network transfer of Event Log Records to be logged or recorded in a central location	.
 * In order to run the following class , please refer to this link($Link) to create the environment.
 * To implement an SCU of a particular we need to do the following things:
 * Create the SCUSession object which maintains the current session of the SCU. Its "start" method accepts
 * the SCP's IP Address and Port and tries to establish a connection with the SCP.
 * 
 * Next step is to establish association .Some ways to create an Association Request: 
 * 1)Use Default Association class to Load the association for requested service. User can load the association 
 * by specifying the Service Type in loadAssociation method of Default association. For e.g. here EnumServiceType.NACTION_AEL
 * should be specified to load Association for N-Action Services. The association request for NACTION_AEL 
 * is made according to  jars in the class path.
 * 2) Manually create object of AssociationRQ class and set all presentation contexts collection on it. 
 * More details provided in the API DOCS of AssociationRQ class.
 * 
 * After successful association is established the SCUSession stores the status of the Association with it.  
 * Create AEL_SCU object to send the N-Action Request to the respective SCP. Currently the "sendMessage" method 
 * of the AEL_SCU would wait after sending the N-Action-RQ until a suitable DIMSE response is received. 
 * This operation is part of Synchronous mode request handling.  
 * Once the DIMSE response is received by the AEL_SCU it stores it into its collection
 * which then can be retrieved.
 * 
 * After this, create a A-Release-RQ in order to request for association release and send it using the
 * SCUSession object. This again is a blocking call and the SCUSession waits until a A-Release-RP is received.
 * 
 * At the end of an operation calling "close" on SCUSession would disconnect the connection made with the 
 * SCP and release all the acquired resources.
 * Instead of closing the session after a N-Action operation is complete,we can create another association
 * and send more requests. 
 * Also it is possible to create multiple N-Action-RQs and send them one by one on the same Association.
 */

public class AppEventLogging_SCU 
{
	public static void main(String[] args)
	{
		DicomConfig objDicomConfig = DicomConfig.createInstance();

		//enable logging,specify the path of the directory where log files are created.
		//User can specify any directory in place of 'c:\DCM_Logs'.
		//If no directory is defined by user to create logs then it is created in User Temp DIR.
		objDicomConfig.enableLogging(EnumLoggingLevel.INFO, "/home/sayali/Desktop/Testing");


		/*
		 * Creates instance of AppEventLogging_SCU
		 */
		AppEventLogging_SCU objTestAEL_SCU = new AppEventLogging_SCU();

		/*
		 * Performs operation of AEL Services 
		 */
		objTestAEL_SCU.doAEL();
	}

	/**
	 * This function performs the operation for all supported services of AEL
	 * AEL operation involves following steps :-
	 * 1. Establish the connection with SCP
	 * 2. Establish the association with SCP
	 * 3. Initializes the SCU for corresponding N-Service and performs the operation using service request
	 * 4. Releases the association after successful processing of service request
	 * 5. Closes the connection with SCP. 
	 */
	public void doAEL()
	{
		try
		{
			/*
			 * *************************************************************************
			 * This block of code performs the connection process with SCP.
			 * It creates the SCUSession and connects with SCP using this session.
			 * *************************************************************************
			 */
			//Create SCUSession object
			SCUSession objSession = new SCUSession();
						
			/*
			 * Setting time out as 5000 milli second. It will wait 5000 mili seconds for read and write operation.
			 * If in the time specified (5000 ms) read or write operation is not performed then 
			 * session is time out.
			 */ 
			//objSession.setTimeOut(5000);

			//Start SCU Session by providing the IP address and Port of SCP.
			objSession.start("localhost", 9000);

			/*
			 * *************************************************************************
			 * This block of code initializes the DefaultAssociation information
			 * Using the DefaultAssociation it generates the Association Request and 
			 * creates association with SCP.
			 * *************************************************************************
			 */

			// Initializes the service types and loads the Default Association for N-Action  Application Event Logging.
			EnumServiceType[] arrenumServiceType = new EnumServiceType[1];
			arrenumServiceType[0] = EnumServiceType.NACTION_AEL;
			DefaultAssociation objDefaultAssociation = new DefaultAssociation("SDK");
			objDefaultAssociation.loadAssociation(arrenumServiceType);

			//Create Association RQ
			AssociateRQ objAssociateRQ = objDefaultAssociation.getAssociationRQ("SDK");

			//Send the Association Request
			if(objSession.sendAssociationMessage(objAssociateRQ))
			{	
				//When association is successfully established the "objSession.sendAssociationMessage()" method returns true.
				System.out.println("Association established");

				/*
				 * *************************************************************************
				 * This block of code creates the NCreate SCU to perform the process of 
				 * SOP Instance creation operation for AEL.
				 * It initializes the NAction RQ and sends it to SCP.
				 * *************************************************************************
				 */
				//Create AEL SCU object using the current SCU Session.
				AEL_SCU objAEL_SCU = new AEL_SCU(objSession);

				//Generating Dataset for AEL
				ProcedureLogIOD objProcedureLogIOD = getTemplateDataSet();
				IDataSet objPELDataSet = objProcedureLogIOD.getDataSet();

				NActionRQ objNActionRQ = NActionRQ.getDefaultRQ(EnumSOPClassUIDs.PROCEDURALEVENTLOGGING.getValue(),DicomConstants.DCM_PROCEDURE_EVENT_LOGGING_SOP_INSTANCE,EnumActionTypeID.APPLICATION_EVENT_LOGGING,objPELDataSet);
				if(objNActionRQ == null)
				{
					System.out.println("Necessary parameters missing while creating Request.");
				}
				else
				{
					System.out.println("N-Action Request for AEL is created");
				}

				//sending RQ to SCP
				if(objAEL_SCU.sendMessage(objNActionRQ))
				{//sending request
					System.out.println("AEL Operation performed");
				}
				else
				{
					System.out.println("AEL failed");
//					In case an ABORT is received from SCP during the AEL operation
					if(objSession.getDIMSEAssociation() instanceof AAbort)
					{
						System.out.println("Abort arrives. Closing session.");
						objSession.close();
					}
				}

				//==============display status
				if(objAEL_SCU.getDIMSEResponse().size() >0)
				{
					NActionRSP objActionRSP = new NActionRSP(objAEL_SCU.getDIMSEResponse().elementAt(0)); 
					System.out.println("Application Event Logging Status : " + objActionRSP.getStatus());
				}

				/*
				 * *************************************************************************
				 * This block of code releases the association and 
				 * removes the connection with SCP.  
				 * *************************************************************************
				 */
				//Create A-Release-RQ to release the association
				AReleaseRQorRP objAReleaseRQorRP = new AReleaseRQorRP(EnumPDUType.RELEASE_RQ);

				//Send the A-Release-RQ
				if(objSession.sendAssociationMessage(objAReleaseRQorRP))
				{
					System.out.println("Association is Released");
					//When successful A-Release-RP is received, close the Session.
					//Please note that instead of closing the session we can create 
					//another association and send more requests. Also it is possible
					//to create multiple N-Services-RQs and send them one by one.
					objSession.close();
				}
			}
			else
			{
				System.out.println("Association cannot be extablished");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	/*
	 * Populates the DataSet with modified values for AEL.
	 * It populates the Dataset manually using some default values of Dataelements for AEL.
	 * This Dataset can be generated using some file also.
	 * @return objIDataSet instance of IDataSet.
	 */
	private ProcedureLogIOD getPELIODForNAction()
	{

		/*
		 * N-Action request data set for Application Event Logging can be created by using
		 * SRDocumant and SRNode. 
		 */
		ProcedureLogIOD objProcedureLogIOD = new ProcedureLogIOD();

		objProcedureLogIOD.getGeneralStudyModule().setStudyInstanceUID("1.2.3.4.5.666");

		// TO CREATE SR TREE
		SRDocumentContentModule objDocumentContentModule = objProcedureLogIOD.getSRDocumentContentModule();

		SRDocument objDocument = new SRDocument();
		SRNode objRoot = objDocument.createRoot(objDocumentContentModule, EnumRelationshipType.CONTAINS, "PROCEDURE LOG", "2345", "DCM", EnumContinuityOfContent.CONTINUOUS);

		objRoot.addPnameNode("TYPE", "5678", "LN", "Device", EnumRelationshipType.HAS_ACQUISITION_CONTEXT);

		SRNode objNode = objRoot.addPnameNode("Observer Name", "5678", "SRT", "XYZ", EnumRelationshipType.CONTAINS);

		objNode.addPnameNode("Observer Type 1", "2357", "DCM", "ABC", EnumRelationshipType.HAS_OBSERVATION_CONTEXT);
		SRNode node = objNode.addPnameNode("Observer Type 2", "2357", "DCM", "Yahoo", EnumRelationshipType.HAS_PROPERTIES);

		node.addTextNode("Observer Type 3", "2357", "DCM", "Yahoo3", EnumRelationshipType.INFERRED_FROM);
		SRNode node2 = node.addTimeNode("TIME", "78768", "SRT", "105700", EnumRelationshipType.SELECTED_FROM);

		node2.addDateTimeNode("DATETIME", "36456", "DCM", "20160622121212", EnumRelationshipType.INFERRED_FROM);

		objNode.addDateTimeNode("rtert", "rte", "reter", "20160622121212", EnumRelationshipType.INFERRED_FROM);
		objNode.addUIDREFNode("UIDREF", "5675", "DCM", "uidref", EnumRelationshipType.INFERRED_FROM);

		SRNode containerNode = objRoot.addContainerNode("CONTAINER", "1111", "DCM", EnumContinuityOfContent.SEPARATE, EnumRelationshipType.CONTAINS);
		containerNode.addPnameNode("Pname", "578", "CSD", "LMN", EnumRelationshipType.HAS_ACQUISITION_CONTEXT);

		objNode.addCodeNode("CODE", "76858", "DCM", "5667", "DCM", "v3", "code", EnumRelationshipType.CONTAINS);

		String[] arr = { "123", "321", "132" };
		objNode.addNumNode("NUM", "34545", "DCM", arr, "0780", "UL", "2b", "deg", "codemeaning", "345", "DCM", "sdf", EnumRelationshipType.CONTAINS);

		objNode.addCompositeNode("COMPOSITE", "34545", "CSD", "45.67.2.45", "678.890.345.4.4", EnumRelationshipType.CONTAINS);

		short[] arrsh ={ (short)4, (short)7, (short)24 };
		objNode.addWaveformNode("WAVEFORM", "346", "DCM", "567.95.3.3", "345.78.23.3", arrsh, EnumRelationshipType.HAS_ACQUISITION_CONTEXT);

		objRoot.addDateTimeNode("TIME", "345", "DCM", "20160622045010", EnumRelationshipType.CONTAINS);

		float[] arrf = { (float)12.45, (float)34.76, (float)889.345 };
		objRoot.addSCOORDNode("SCOORD", "345345", "SRT", arrf, EnumGraphicType.CIRCLE, EnumRelationshipType.SELECTED_FROM);

		String[] stra = { "20160622045010", "20160622045010", "20160622045010" };
		int[] larr = { 6, 7, 8 };
		String[] strb = { "045010", "045010", "045010" };
		objRoot.addTCOORDNode("TCOORD", "67567", "DCM", stra, larr, strb, EnumTemporalRangeType.BEGIN, EnumRelationshipType.HAS_PROPERTIES);

		String[] arrst = { "122", "221" };
		short shBitsAllocated = 34;
		ImagePixelMacro objImagePixelMacro = objRoot.addImageNode("IMAGE", "45345", "DCM", "345.456.456.6.6.6", "35.5.5.5", arrst, "234.45.345", "5675.567.67567", EnumRelationshipType.CONTAINS);
		objImagePixelMacro.setBitsAllocated(shBitsAllocated);

		return objProcedureLogIOD;
	}

	/**
	 * Method uses the Content Mapping Resource to create the dataset
	 * @return objProcedureLogIOD - Object of ProcedureLogIOD
	 */
	@SuppressWarnings("unused")
	private ProcedureLogIOD getTemplateDataSet()
	{
		/*
		 * The data set of Application Event Logging i.e. N-Action Request can be created using Content Resource Mapping.
		 */
		ProcedureLogIOD objProcedureLogIOD = new ProcedureLogIOD();

		objProcedureLogIOD.getGeneralStudyModule().setStudyInstanceUID("1.1.1.1.2.2.2");

		SRDocumentContentModule objDocumentContentModule = objProcedureLogIOD.getSRDocumentContentModule();

		SRTree objTree = new SRTree(objDocumentContentModule);

		ProcedureLog_TID3001 objProcedureLog = new ProcedureLog_TID3001(objTree);

		objProcedureLog.setProcedureLogTitle(EnumCM_ProcedureLogTitles.CATH_LAB_PROCEDURE_LOG, EnumContinuityOfContent.SEPARATE);

		int[] arr1 = { 1, 1 };
		objProcedureLog.getObserverContext().setObserverType(arr1, EnumCM_ObserverType.PERSON, "");

		int[] arr2 = { 1, 2 };
		objProcedureLog.getIntervention_TID3108().setProcedureSite(arr2, EnumCM_ArterialSourceLocations.AORTA);

		int[] arr3 = { 1, 3 };
		objProcedureLog.getDrugsContrastAdministered_TID3106().setRouteOfAdministration(arr3, EnumCM_RouteOfAdministration.INTRAEPITHELIAL_ROUTE);

		int[] arr4 = { 1, 4 };
		objProcedureLog.getLesionIdentificationAndProperties().getLogEntryQualifiers().setObservationDateTimeQualifiers(arr4, EnumCM_DateTimeQualifiers.DATETIME_UNSYNCHRONIZED, "wwe");

		int[] arr5 = { 1, 5 };
		objProcedureLog.setStaffAction(arr5, EnumCM_StaffAction.PAGE_SENT_TO, "PNAME");

		int[] arr6 = { 1, 6 };
		objProcedureLog.getDrugsContrastAdministered_TID3106().setRouteOfAdministration(arr6, EnumCM_RouteOfAdministration.INTRACARDIAC_ROUTE);

		int[] arr7 = { 1, 7 };
		objProcedureLog.setStatusOrEvent(arr7, EnumCM_PatientStatusAndEvents.NIL_PER_OS_NPO_STATUS_CONFIRMED, "xyz");

		int[] arr8 = { 1, 8 };
		objProcedureLog.getConsumables().setActionsWithConsumables(arr8, EnumCM_ActionsWithConsumables.CONSUMABLE_TAKEN_FROM_INVENTORY, "gfg");

		
		

		return objProcedureLogIOD;
	}

	/*
	 * Creates DataElement for given Group and Element Number
	 */
	@SuppressWarnings("unused")
	private IDataElement getDataElement(int GroupNo,int ElementNo,Object objVal,IDictionaryReader objDictionaryReader)
	{
		IDataElement objIDataElement = new ImplicitDE(GroupNo, ElementNo,objVal,objDictionaryReader);
		return objIDataElement;
	}

	/*
	 * Creates SQ for given Group and Element Number
	 */
	@SuppressWarnings("unused")
	private IDataTypeSQ getSQ(int GroupNo,int ElementNo , ITransferSyntax objTS)
	{
		return DicomV3Factory.createInstance().createSequence(GroupNo, ElementNo, objTS);
	}
}
