/*******************************************************************************
 *  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.ianservice.testcases.scu;

import cdac.medinfo.sdk.dcm30_04.baselibs.DataSet;
import cdac.medinfo.sdk.dcm30_04.baselibs.DicomV3Factory;
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.IItem;
import cdac.medinfo.sdk.dcm30_04.commoninterface.ITransferSyntax;
import cdac.medinfo.sdk.dcm30_04.enums.EnumLoggingLevel;
import cdac.medinfo.sdk.dcm30_04.enums.EnumPDUType;
import cdac.medinfo.sdk.dcm30_04.enums.EnumSOPClassUIDs;

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.EnumServiceType;
import cdac.medinfo.sdk.dcm30_04.services.ian.scu.IAN_SCU;
import cdac.medinfo.sdk.dcm30_04.services.ncreate.commons.NCreateRQ;
import cdac.medinfo.sdk.dcm30_04.services.ncreate.commons.NCreateRSP;
import cdac.medinfo.sdk.dcm30_04.services.scu.commons.SCUSession;
import cdac.medinfo.sdk.dcm30_04.utils.DicomConfig;

/**
 * This sample code specifies the role of IAN service class user.
 * It uses IAN SCU to send the request to SCP.
 * IAN service class supports NCreate service :-
 * 
 * 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 Services Type in loadAssociation method of Default association.
 * 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 respective SCU object to send the service Request to the SCP. Currently the "sendMessage" method 
 * of the respective SCU would wait after sending the service DIMSE-RQ until a suitable DIMSE-RSP is received. 
 * This operation is part of Synchronous mode request handling.  
 * Once the DIMSE response is received by the 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 service operation is complete,we can create another association
 * and send more requests. 
 * Also it is possible to create multiple service requests and send them one by one on the same Association.
 */
public class IAN_SCU_Test 
{
	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, "C:\\DCM_Logs");

		/*
		 * Creates instance of IAN_SCU_Test
		 */
		IAN_SCU_Test objTestIAN_SCU = new IAN_SCU_Test();

		/*
		 * Performs operation of IAN Services 
		 */
		objTestIAN_SCU.doIAN();
	}

	/**
	 * This function performs the operation for all supported services of IAN
	 * IAN 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 doIAN()
	{
		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("192.168.8.94", 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 populates the Default Association
			EnumServiceType[] arrenumServiceType = new EnumServiceType[1];
			arrenumServiceType[0] = EnumServiceType.NCREATE_IAN;
			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 IAN SCU to perform the process of 
				 * SOP Instance creation operation for IAN.
				 * It initializes the NCreate RQ and sends it to SCP.
				 * *************************************************************************
				 */
				//Create IAN SCU object using the current SCU Session.
				IAN_SCU objIAN_SCU = new IAN_SCU(objSession);

				//Generating Dataset for IAN
				IDataSet objIANDataSet = getIANForCreate();
				//Initializing NCreate RQ 
				NCreateRQ objNCreateRQ = NCreateRQ.getDefaultRQ(EnumSOPClassUIDs.INSTANCEAVAILABILITYNOTIFICATION.getValue(), "1.3.12.2.1107.5.1.4.36085.4.0.11", objIANDataSet);
				System.out.println("IAN Request For N-Create Initialized");

				//sending RQ to SCP
				if(objIAN_SCU.sendMessage(objNCreateRQ)) //sending request
				{
					System.out.println("IAN Instance Creation Operation performed");
					NCreateRSP objNCreateRSP = new NCreateRSP(objIAN_SCU.getDIMSEResponse().get(0));
					System.out.println("N-Create Response Status :" + objNCreateRSP.getStatus());
				}
				else
					System.out.println("IAN Instance Creation Operation failed");


				/*
				 * *************************************************************************
				 * 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))
				{
					//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-Service-RQs and send them one by one.
					objSession.close();
				}

				//In case an ABORT is received from SCP during the IAN operation
				if(objSession.getDIMSEAssociation() instanceof AAbort)
				{
					System.out.println("Abort arrives. Closing session.");
					objSession.close();
				}
			}
			else
			{
				System.out.println("Association cannot to extablished");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	/*
	 * Populates the DataSet with modified values for IAN.
	 * It populates the Dataset manually using some default values of Dataelements for IAN.
	 * This Dataset can be generated using some file also.
	 * @return objIDataSet instance of IDataSet.
	 */
	private IDataSet getIANForCreate()
	{
		IDataSet objIDataSet = new DataSet();
		IDictionaryReader objDictionaryReader = objIDataSet.getDictionaryReader();
		ITransferSyntax objTS = objIDataSet.getTransferSyntax();

		String []arrstrSpecificCharSet = new String[2];
		arrstrSpecificCharSet[0] = "ISO-IR 6";
		arrstrSpecificCharSet[1] = "ISO-IR 100";

		objIDataSet.addDataElement(getDataElement(0x0008,0x0005,arrstrSpecificCharSet, objDictionaryReader));
		{
			IDataTypeSQ objReferencedPerformedProcedureStepSQ = getSQ(0x0008,0x1111, objTS);
			IItem objReferencedPerformedProcedureStepItem = objReferencedPerformedProcedureStepSQ.getNewItem();

			objReferencedPerformedProcedureStepItem.addDataElement(getDataElement(0x0008,0x1150, "1.2.840.10008.5.1.4.1.1.12.1", objDictionaryReader));
			objReferencedPerformedProcedureStepItem.addDataElement(getDataElement(0x0008,0x1155, "1.3.12.2.1107.5.4.3.284980.19951129.170916.11", objDictionaryReader));
			{
				IDataTypeSQ objPerformedWorkitemCodeSQ = getSQ(0x0040,0x4019, objTS);
				IItem objPerformedWorkitemCodeItem = objPerformedWorkitemCodeSQ.getNewItem();
				objPerformedWorkitemCodeItem.addDataElement(getDataElement(0x0008,0x0100,"Code", objDictionaryReader));
				objPerformedWorkitemCodeItem.addDataElement(getDataElement(0x0008,0x0102,"Coding", objDictionaryReader));
				objPerformedWorkitemCodeItem.addDataElement(getDataElement(0x0008,0x0104,"Code", objDictionaryReader));

				objPerformedWorkitemCodeSQ.addItem(objPerformedWorkitemCodeItem);
				objReferencedPerformedProcedureStepItem.addDataElement(getDataElement(0x0040,0x4019,objPerformedWorkitemCodeSQ.getValue(), objDictionaryReader));
			}
			objReferencedPerformedProcedureStepSQ.addItem(objReferencedPerformedProcedureStepItem);
			objIDataSet.addDataElement(getDataElement(0x0008,0x1111,objReferencedPerformedProcedureStepSQ.getValue(), objDictionaryReader));
			objIDataSet.addDataElement(getDataElement(0x0020,0x000D,"1.3.12.2.1107.5.4.3.4975316777216.19951114.94101.16", objDictionaryReader));

			{
				IDataTypeSQ objReferencedSeriesSQ = getSQ(0x0008,0x1115, objTS);
				IItem objReferencedSeriesItem = objReferencedSeriesSQ.getNewItem();
				objReferencedSeriesItem.addDataElement(getDataElement(0x0020,0x000E,"1.3.12.2.1107.5.4.3.4975316777216.19951114.94101.17", objDictionaryReader));
				{
					IDataTypeSQ objReferencedSOPSQ = getSQ(0x0008,0x1199, objTS);
					IItem objReferencedSOPItem = objReferencedSOPSQ.getNewItem();
					objReferencedSOPItem.addDataElement(getDataElement(0x0008,0x1150,"1.2.840.10008.5.1.4.1.1.12.1", objDictionaryReader));
					objReferencedSOPItem.addDataElement(getDataElement(0x0008,0x1155,"1.3.12.2.1107.5.4.3.284980.19951129.170916.11", objDictionaryReader));
					objReferencedSOPItem.addDataElement(getDataElement(0x0008,0x0056,"12345", objDictionaryReader));
					objReferencedSOPItem.addDataElement(getDataElement(0x0008,0x0054,"SDK", objDictionaryReader));
					objReferencedSOPItem.addDataElement(getDataElement(0x0088,0x0130,"1", objDictionaryReader));
					objReferencedSOPItem.addDataElement(getDataElement(0x0088,0x0140,"2", objDictionaryReader));

					objReferencedSOPSQ.addItem(objReferencedSOPItem);
					objReferencedSeriesItem.addDataElement(getDataElement(0x0008,0x1199,objReferencedSOPSQ.getValue(), objDictionaryReader));
				}
				objReferencedSeriesSQ.addItem(objReferencedSeriesItem);
				objIDataSet.addDataElement(getDataElement(0x0008,0x1115,objReferencedSeriesSQ.getValue(), objDictionaryReader));
			}
		}

		return objIDataSet;
	}

	/*
	 * Creates DataElement for given Group and Element Number
	 */
	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
	 */
	private IDataTypeSQ getSQ(int GroupNo,int ElementNo , ITransferSyntax objTS)
	{
		return DicomV3Factory.createInstance().createSequence(GroupNo, ElementNo, objTS);
	}
}
