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


import cdac.medinfo.sdk.dcm30_04.commoninterface.IDataSet;
import cdac.medinfo.sdk.dcm30_04.dicommodel.ct.CTIOD;
import cdac.medinfo.sdk.dcm30_04.dicommodel.sc.SCIOD;
import cdac.medinfo.sdk.dcm30_04.dicommodel.xray.XRayAngiographicIOD;
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.association.RQPresContext;
import cdac.medinfo.sdk.dcm30_04.services.cstore.commons.CStoreRQ;
import cdac.medinfo.sdk.dcm30_04.services.cstore.commons.CStoreRSP;
import cdac.medinfo.sdk.dcm30_04.services.cstore.scu.CStoreSCU;
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-Store SCU in Asynchronous Mode.
 * In Asynchronous Mode SCU sends multiple service request to SCP without waiting for the Response.
 * To implement C-Store SCU in Asynchronous mode user needs to implement interface IAsyncReceiver and should give 
 * implementation of onResponseReceive() and getNoOfRemainingResponses() method.
 * The IAsyncReceiver should be added  to SCU session to receive the response. Whenever a response 
 * is received by SCU Session, call back is made on onResponseReceive() method of the test code.
 * 
 * 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.CSTORE
 * should be specified to load Association for C-Store Services. The association request for C-Store 
 * 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 CStoreSCU object to send the C-Store Request to the respective SCP. The "sendMessage" method 
 * of the CStoreSCU would not wait after sending the C-Store-RQ.  
 * All C-Store requests are sent without waiting for the response to receive.As the request are processed at the SCP
 * the response is received by the SCU. Presently the test code itself is IAsyncReceiver . 
 * So when the C-Store RSP is received then onResponseReceive method is called.
 * The response can be added in the collection there.
 * 
 * When all the C-Store response is received then Association release request is sent.
 * 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-Store operation is complete,we can create another association
 * and send more requests. 
 */
public class CStore_SCU_Async implements IAsyncReceiver
{

	//Current SCU Session
	SCUSession objSession;

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

	//Count variable
	int count =1;


	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");

		CStore_SCU_Async objTestAsyncCStoreSCU = new CStore_SCU_Async();

		objTestAsyncCStoreSCU.start();
	}

	/**
	 * This function performs the CStore operation.
	 */
	public void start()
	{
		try
		{
			IDataSet[] arrIDataSet = new IDataSet[4];

			// Enter the X-Ray Angiogram DICOM File with full path
			String strFilePath = null;
			System.out.println("Enter the X-Ray Angiogram Dicom File with complete path");
			BufferedReader b_reader =new BufferedReader( new InputStreamReader( System.in ) );
			strFilePath = b_reader.readLine();

			// Creates the object of corresponding IOD by calling its constructor which takes File Name as a parameter and give its DataSet.
			XRayAngiographicIOD objXRayAngiographicIOD = new XRayAngiographicIOD(strFilePath);
			arrIDataSet[0] = objXRayAngiographicIOD.getDataSet();

			// Enter the 0003.dcm DICOM File with full path
			System.out.println("Enter the 0003.dcm Dicom File with complete path");
			b_reader =new BufferedReader( new InputStreamReader( System.in ) );
			strFilePath = b_reader.readLine();

			// Creates the object of corresponding IOD by calling its constructor which takes File Name as a parameter and give its DataSet.
			objXRayAngiographicIOD = new XRayAngiographicIOD(strFilePath);
			arrIDataSet[1] = objXRayAngiographicIOD.getDataSet();

			// Enter the CT-Dicom-File.dcm DICOM File with full path
			System.out.println("Enter the CT-Dicom-File.dcm Dicom File with complete path");
			b_reader =new BufferedReader( new InputStreamReader( System.in ) );
			strFilePath = b_reader.readLine();

			// Creates the object of corresponding IOD by calling its constructor which takes File Name as a parameter and give its DataSet.
			CTIOD objCTIOD = new CTIOD(strFilePath);
			arrIDataSet[2] = objCTIOD.getDataSet();

			// Enter the SC-ankle.dcm DICOM File with full path
			System.out.println("Enter the SC-ankle.dcm Dicom File with complete path");
			b_reader =new BufferedReader( new InputStreamReader( System.in ) );
			strFilePath = b_reader.readLine();

			// Creates the object of corresponding IOD by calling its constructor which takes File Name as a parameter and give its DataSet.
			SCIOD objSCIOD = new SCIOD(strFilePath);
			arrIDataSet[3] = objSCIOD.getDataSet();

			//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);

			/*
			 * Creating RQPresContext for which C-Store is to be performed.
			 */
			ISingleCollection<RQPresContext> objRQPresContextCol = new SingleCollection<RQPresContext>();

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

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

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

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

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

			//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.
			 */
			objSession.start("192.168.8.94", 9000);

			/*
			 * Create C-Store SCU.
			 */
			CStoreSCU objCStoreSCU = new CStoreSCU(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");
				for(int i=0; i<4;i++)
				{
					//Create Default CStore 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.
					CStoreRQ objCStoreRQ = CStoreRQ.getDefaultRQ(arrIDataSet[i]);

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

					//Send the C-Store-RQ .
					//In async mode all the C-Store request is sent without waiting 
					//for response.When the response is received then onResponseReceived method is called.
					if(objCStoreSCU.sendMessage(objCStoreRQ))
					{
						System.out.println("Storage Request Sent");
					}
					else
					{
						System.out.println("C-Store Operation failed ");
					}
				}

				//Create A-Release-RQ to release the association
				AReleaseRQorRP objAReleaseRQorRP = new AReleaseRQorRP(EnumPDUType.RELEASE_RQ);

				System.out.println("Association status is *************************************** "+objSession.getAssociationStatus());

				//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-Store-RQs and send them one by one.
				if(objSession.sendAssociationMessage(objAReleaseRQorRP))
				{
					System.out.println("Associaiton is released");
					objSession.close();
				}

				System.out.println("Response Collection Size "+objCStoreSCU.getDIMSEResponse().size());


				//In case an ABORT is received from SCP during the C-Store operation
				if(objSession.getDIMSEAssociation() instanceof AAbort)
				{
					System.out.println("Abort Arrives. Closing SCU session.");
					objSession.close();
				}
			}
			else
			{
				System.out.println("Association cannot to extablished");
				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 called when the response of the request sent is received.
	 */
	public void onResponseReceive(DicomMessage response) throws IOException
	{
		System.out.println("Response received ..............................................." + count);
		count++;
		cStoreRespCollection.add(response);
		CStoreRSP objCStoreRSP = new CStoreRSP(response);
		System.out.println("C-Store Response Status : " +objCStoreRSP.getStatus());
	}
}
