/*******************************************************************************
 *  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 java.io.IOException;


import cdac.medinfo.sdk.dcm30_04.baselibs.DataSet;
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.IDictionaryReader;
import cdac.medinfo.sdk.dcm30_04.enums.EnumCommandField;
import cdac.medinfo.sdk.dcm30_04.enums.EnumLoggingLevel;
import cdac.medinfo.sdk.dcm30_04.enums.EnumPDUType;

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.cmove.commons.CMoveRQ;
import cdac.medinfo.sdk.dcm30_04.services.cmove.commons.CMoveRSP;
import cdac.medinfo.sdk.dcm30_04.services.cmove.scu.CMoveSCU;
import cdac.medinfo.sdk.dcm30_04.services.dicomnetcommons.EnumServiceType;
import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.CCancelRQ;
import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.DicomMessage;
import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.IAsyncReceiver;
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.ISingleCollection;
import cdac.medinfo.sdk.dcm30_04.utils.SingleCollection;

/**
 * This class is implemented to test the C-Move 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
 * After successful association is established the SCUSession stores the status of the Association with it.  
 * Create C-Move object to send the C-Move Request to the respective SCP.
 * In Async Mode all the requests are send using "sendMessage" method of C-Move SCU. 
 * 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.
 * All C-Move requests are sent without waiting for the response to receive. 
 * When C-Move response is received then call back is made on IAsyncreceiver.
 * Presently the test code itself is IAsyncReceiver . So when the C-Move RSP is received then
 * onResponseReceive method is called. The response can be added in the collection there. 
 * Once the DIMSE response is received by the MoveSCU it stores it into its collection
 * which then can be retrieved.
 * When all the C-Move response is received then Association release response 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-Store operation is complete,we can create another association
 * and send more requests. 
 * When CMove request is send to the server with key attribute which is to be moved then for the Destination AE Title
 * specified in the CMove request, the C-Move Server should perform the CStore with third party and sends 
 * response to SCU. Once the DIMSE response is received by the CMoveSCU it stores it into its collection
 * which then can be retrieved.
 * 
 * In addition to above this test code also illustrate use of C-CANCEL request. Which can be used to cancel the processing of previously 
 * sent C-Move request.
 */
public class CMove_SCU_Async_with_C_CANCEL implements IAsyncReceiver
{
	//	SCUSession 
	SCUSession objSession;

	//	Collection containing C-Move Response.
	ISingleCollection<DicomMessage> CMoveRespCollection = new SingleCollection<DicomMessage>();

	public static void main(String[] args)
	{
		try
		{
			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'.
			objDicomConfig.enableLogging(EnumLoggingLevel.INFO, "C:\\DCM_Logs");
			/*
			 * create instance of CMove_SCU_Async_with_C_CANCEL.
			 */
			CMove_SCU_Async_with_C_CANCEL objTestCMoveSCU = new CMove_SCU_Async_with_C_CANCEL();

			objTestCMoveSCU.start();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * Start C-Move operation.
	 */
	public void start()
	{
		try
		{
			//Create SCUSession object
			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);

			//Add test code as Async Receiver to get the response.
			objSession.addAsyncReceiver(this);

			/*
			 * Initializing selected services and loading default association
			 */
			EnumServiceType[] arrenumServiceType = new EnumServiceType[1];
			arrenumServiceType[0] = EnumServiceType.CMOVE;
			DefaultAssociation objDefaultAssociation = new DefaultAssociation("SDK");
			objDefaultAssociation.loadAssociation(arrenumServiceType);

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

			/*
			 * Change Association request for Async Operation.
			 * Set Maximum Number of operation invoked and performed in RQUserInfo.
			 * If the value of Max number of Operation performed and invoked is zero 
			 * then it means it is unbounded.
			 */
			objAssociateRQ.getRQUserInfo().setMaxNumOpsInvoked((short)0);
			objAssociateRQ.getRQUserInfo().setMaxNumOpsPerformed((short)0);

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

			//Create CStore SCU object using the current SCU Session.
			CMoveSCU objCMoveSCU = new CMoveSCU(objSession);

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

				for(int i=0;i<25;i++)
				{
					/*
					 * get C-Move DataSet
					 */
					IDataSet objIDataSet = new DataSet();
					IDictionaryReader objIDictionaryReader = objIDataSet.getDictionaryReader();
					//					//Sending StudyInstanceUID for query
					IDataElement objIDataElement = new ImplicitDE(0x0020,0x000D,"1.3.12.2.1107.5.4.3.4975316777216.19951114.94101.16",objIDictionaryReader);
					objIDataSet.addDataElement(objIDataElement);

					//Create Default CMove RQ by giving the parsed DataSet. This method uses
					// default values for the attributes in the request. These attributes can be
					//modified once the request object is created, before sending.
					CMoveRQ objCMoveRQ = CMoveRQ.getDefaultRQ(DicomConstants.DCM_STUDY_ROOT_QUERY_OR_RETRIVE_INFORMATION_MODEL_MOVE, "DCMRCV", objIDataSet);


					//sending request for C-Move
					if(objCMoveSCU.sendMessage(objCMoveRQ))
					{
						System.out.println("C-Move Request Sent");
					}
					else
					{
						System.out.println("C-Move Request Cannot be Sent");
					}

					if(i%2==0)
					{
						CCancelRQ objCancelFindRQ = new CCancelRQ();
						objCancelFindRQ.setCommandField(EnumCommandField.C_CANCEL_RQ);
						objCancelFindRQ.setCommandDataSetType(DicomConstants.DCM_DATASET_NOT_PRESENT);
						objCancelFindRQ.setMessageIDBeingRespondedTo(objCMoveRQ.getMessageID());

						if(objCMoveSCU.sendMessage(objCancelFindRQ))
						{
							System.out.println("C-FIND-CANCEL Request for message ID : "+objCMoveRQ.getMessageID() + "  is sent.");
						}
						else
						{
							System.out.println("C-FIND-CANCEL Request for message ID : "+objCMoveRQ.getMessageID() + "  is failed.");
						}

					}
				}

				//sending release request
				AReleaseRQorRP objAReleaseRQorRP = new AReleaseRQorRP(EnumPDUType.RELEASE_RQ);
				if(objSession.sendAssociationMessage(objAReleaseRQorRP))
				{
					System.out.println("Association is released");
					objSession.close();
				}
			}
			else
			{
				System.out.println("Associaiton cannot be established");
				objSession.close();
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
			objSession.close();
		}
	}

	/**
	 * This function gets the number of remaining response.
	 * @return int
	 */
	public int getNoOfRemainingResponses() 
	{
		return objSession.getNumberOfRequestSend() - CMoveRespCollection.size();
	}

	int count =1;

	/**
	 * This method is call backed when Response is received.
	 * @param response  Response received.
	 */
	public void onResponseReceive(DicomMessage response) throws IOException
	{
		System.out.println("Response received ---------------------------------------" + count++);
		CMoveRespCollection.add(response);
		CMoveRSP objCMoveRSP = new CMoveRSP(response);
		System.out.println("C-Move Response Status :" + objCMoveRSP.getStatus());
	}
}
