/*******************************************************************************
 *  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.cservices.testcases.scu;
import cdac.medinfo.sdk.dcm30_04.utils.DicomConstants;


import cdac.medinfo.sdk.dcm30_04.enums.EnumLoggingLevel;
import cdac.medinfo.sdk.dcm30_04.enums.EnumPDUType;

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.AssociateRJ;
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.cecho.commons.CEchoRQ;
import cdac.medinfo.sdk.dcm30_04.services.cecho.commons.CEchoRSP;
import cdac.medinfo.sdk.dcm30_04.services.cecho.scu.CEchoSCU;
import cdac.medinfo.sdk.dcm30_04.services.dicomnetcommons.EnumServiceType;
import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.DicomMessage;
import cdac.medinfo.sdk.dcm30_04.services.scu.commons.SCUSession;
import cdac.medinfo.sdk.dcm30_04.utils.DicomConfig;
import cdac.medinfo.sdk.dcm30_04.utils.ICollectionIterator;
import cdac.medinfo.sdk.dcm30_04.utils.ISingleCollection;

/**
 * This class is implemented to test the C-Echo SCU.
 * 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 with SCP. 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.CECHO
 * should be specified to load Association for C-Echo Services.
 * 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.
 * Use SCUSession object to send the Association-RQ which makes a blocking call and waits until the Associate Response is received.
 * After successful association is established the SCUSession stores the status of the Association with it.  
 * 
 * Create CEchoSCU object to send the C-Echo Request to the respective SCP. Currently the "sendMessage" method 
 * of the CEchoSCU would wait after sending the C-Echo-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 CEchoSCU it stores the DIMSE response 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 C-Echo operation is complete,we can create another association
 * and send more requests. 
 * Also it is possible to create multiple C-Echo-RQs and send them one by one on the same Association.
 */
public class CEcho_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, "C:\\DCM_Logs");

		//Create SCUSession object
		SCUSession objSession =null;

		try
		{
			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);

			/*
			 * Initializing selected services and loading default association
			 */
			EnumServiceType[] arrenumServiceType = new EnumServiceType[1];
			arrenumServiceType[0] = EnumServiceType.CECHO;

			DefaultAssociation objDefaultAssociation = new DefaultAssociation("SDK");
			objDefaultAssociation.loadAssociation(arrenumServiceType);

			//get Association RQ from Default Association.
			AssociateRQ objAssociateRQ = objDefaultAssociation.getAssociationRQ("SDK");

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

			//Create CEchoSCU object using the current SCU Session.
			CEchoSCU objCEchoSCU = new CEchoSCU(objSession);

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

				//use this looping to send multiple requests.
				//int i = 10;
				//while(i-- > 0)
				//{

				//Create Default CEcho RQ . This method uses
				// default values for the attributes in the request. These attributes can be
				//modified once the request object is created, before sending.
				CEchoRQ objCEchoRQ = CEchoRQ.getDefaultRQ(DicomConstants.DCM_VERIFICATION_SOP_CLASS);

				System.out.println("CEcho Request initialized");

				//Send the C-Echo-RQ and wait for a C-Echo-RSP.
				//This method exits once the response is received. This response is 
				//added in the response collection maintained by the CEchoSCU which
				//can be retrieved. This method return true if request is successfully sent 
				//to the SCP and false if the message cannot be sent to the SCP( for e.g. if 
				//the association status is false or if SOP class UID is not agreed in agreed association.
				if(objCEchoSCU.sendMessage(objCEchoRQ))
				{
					System.out.println("CEcho Response Received");
				}
				else
				{
					System.out.println("CEcho Operation cannot be performed");
				}

				System.out.println("Size of Response collection == "+ objCEchoSCU.getDIMSEResponse().size());

				ISingleCollection<DicomMessage> objDicomMessageColl = objCEchoSCU.getDIMSEResponse();
				ICollectionIterator<DicomMessage> itr = objDicomMessageColl.iterator();
				while(itr.hasNext())
				{
					DicomMessage objDicomMessage = itr.next();
					CEchoRSP objEchoRSP = new CEchoRSP(objDicomMessage);
					System.out.println("STATUS : " + objEchoRSP.getStatus());
				}

				//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("Release Response Received ");

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

				//In case an ABORT is received from SCP during the C-Echo operation
				if(objSession.getDIMSEAssociation() instanceof AAbort)
				{
					System.out.println("Abort Arrives. Closing SCU session.");
					objSession.close();
				}
			}
			else
			{
				System.out.println("Associaiton cannot be established");
				AssociateRJ objAssociation = (AssociateRJ)objSession.getDIMSEAssociation();
				System.out.println("Reason : " + objAssociation.getReason());
				objSession.close();
			}

		}
		catch(Exception e)
		{
			e.printStackTrace();
			objSession.close();
		}
	}
}
