/*******************************************************************************
 *  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.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.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.association.RQPresContext;
import cdac.medinfo.sdk.dcm30_04.services.cget.commons.CGetRQ;
import cdac.medinfo.sdk.dcm30_04.services.cget.commons.CGetRSP;
import cdac.medinfo.sdk.dcm30_04.services.cget.scu.CGetSCU;
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-Get 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. There are two methods to
 * create an Association Request: 1)Load Default association on the basic of 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 CGetSCU object to send the C-Get Request to the respective SCP. In Async Mode all the requests
 * are send using "sendMessage" method of C-Get 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-Get requests are sent without waiting for the response to receive. 
 * When C-Get response is received then call back is made on IAsyncreceiver.
 * Presently the test code itself is IAsyncReceiver . So when the C-Get 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 CGetSCU it stores it into its collection
 * which then can be retrieved.
 * When all the C-Get 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-Get operation is complete,we can create another association
 * and send mroe requests. 
 */
public class CGet_SCU_Async implements IAsyncReceiver
{
	//Current SCU Session
	SCUSession objSession;

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

	int count = 0;

	public static void main(String[] args) throws IOException
	{
		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");

		/*
		 * Creates instance of CGet_SCU_Async and start Get SCU operation.
		 */
		CGet_SCU_Async objTestAsyncGetSCU = new CGet_SCU_Async();
		objTestAsyncGetSCU.start();
	}

	/**
	 * Starts CGet 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 Async Receiver to Session.
			objSession.addAsyncReceiver(this);

			/*
			 * Initializes the service types and populates the default association
			 */
			RQPresContext objRQPresContextCGET = new RQPresContext();
			objRQPresContextCGET.setAbstractSyntaxName(EnumSOPClassUIDs.PATIENTROOTQUERYGET.getValue());
			objRQPresContextCGET.addTransferSyntax(DicomConstants.TS_DEFAULT_IMPLICIT_VR_LITTLE_ENDIAN);

			//RQ Pres Context for X-Ray
			RQPresContext objRQPresContextXRay = new RQPresContext();
			objRQPresContextXRay.setAbstractSyntaxName(EnumSOPClassUIDs.XRAYANGIOGRAPHICIOD.getValue());
			objRQPresContextXRay.addTransferSyntax(DicomConstants.TS_LOSSY_JPEG_8_BIT);

			//RQ Pres Context for CT
			RQPresContext objRQPresContextCT = new RQPresContext();
			objRQPresContextCT.setAbstractSyntaxName(EnumSOPClassUIDs.CTIOD.getValue());
			objRQPresContextCT.addTransferSyntax(DicomConstants.TS_DEFAULT_IMPLICIT_VR_LITTLE_ENDIAN);

			//RQ Pres Context for NM
			RQPresContext objRQPresContextNM = new RQPresContext();
			objRQPresContextNM.setAbstractSyntaxName(EnumSOPClassUIDs.NMIOD.getValue());
			objRQPresContextNM.addTransferSyntax(DicomConstants.TS_EXPLICIT_VR_LITTLE_ENDIAN);

			//RQ Pres Context for SC
			RQPresContext objRQPresContextSC = new RQPresContext();
			objRQPresContextSC.setAbstractSyntaxName(EnumSOPClassUIDs.SCIOD.getValue());
			objRQPresContextSC.addTransferSyntax(DicomConstants.TS_DEFAULT_IMPLICIT_VR_LITTLE_ENDIAN);

			ISingleCollection<RQPresContext> objPressConColl = new SingleCollection<RQPresContext>();
			objPressConColl.add(objRQPresContextXRay);
			objPressConColl.add(objRQPresContextCT);
			objPressConColl.add(objRQPresContextNM);
			objPressConColl.add(objRQPresContextSC);
			objPressConColl.add(objRQPresContextCGET);


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

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

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

			/*
			 * Start SCU Session.
			 */
			objSession.start("192.168.8.94", 9000);

			/*
			 * Create C-Get SCU.
			 */
			CGetSCU objCGetSCU = new CGetSCU(objSession);

			//Destination where the retrieved DataSet is stored.
			objCGetSCU.setDestinationPath("C:\\GetFiles");

			/*
			 * Send the Association Request.
			 */
			if(objSession.sendAssociationMessage(objAssociateRQ))
			{
				System.out.println("Association is established");

				for(int i=0;i<4;i++)
				{
					/*
					 * Get C-Get Data Set.
					 */
					IDataSet objIDataSet = new DataSet();
					IDictionaryReader objIDictionaryReader = objIDataSet.getDictionaryReader();
					//query parameter PatientID
					IDataElement objIDataElement = new ImplicitDE(0x0010,0x0020,"322-292-73-6",objIDictionaryReader);
					objIDataSet.addDataElement(objIDataElement);

					//Create Default CGetRQ 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.
					CGetRQ objCGetRQ = CGetRQ.getDefaultRQ(EnumSOPClassUIDs.PATIENTROOTQUERYGET.getValue(),objIDataSet);

					//sending CGet Request
					if(objCGetSCU.sendMessage(objCGetRQ))
					{
						System.out.println("C-Get Request Sent");
					}
					else
					{
						System.out.println("C-Get Operation failed");
					}

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

	/**
	 * Gets the no of remaining responses.
	 * @return int
	 */
	public int getNoOfRemainingResponses() 
	{
		return objSession.getNumberOfRequestSend() - cStoreRespCollection.size();
	}

	/**
	 * 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++);
		cStoreRespCollection.add(response);
		CGetRSP objCGetRSP = new CGetRSP(response);
		System.out.println("C-Get Reponse Status "+ objCGetRSP.getStatus());
	}
}
