/*******************************************************************************
 *  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.SubstanceAdministration.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.baselibs.SQ;
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.commoninterface.IItem;
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.AssociateRQ;
import cdac.medinfo.sdk.dcm30_04.services.association.DefaultAssociation;
import cdac.medinfo.sdk.dcm30_04.services.cfind.commons.CFindRQ;
import cdac.medinfo.sdk.dcm30_04.services.cfind.commons.CFindRSP;
import cdac.medinfo.sdk.dcm30_04.services.cfind.scu.CFindSCU;
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 SubstanceAdministrationInfoQry SCU using CFindSCU class of SDK for DICOM.
 * 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. 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.CFind
 * should be specified to load Association for C-Find services. The association request for C-Find 
 * 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 CFind object to send the C-Find Request to the respective SCP. Currently the "sendMessage" method 
 * of the SubstanceAdministrationInfoQrySCU would wait after sending the C-Find-RQ until a suitable DIMSE response is received. 
 * When CFind request is send to the server with key attribute to be searched in the data set
 * then for the matches find (for key attribute at SCP side) it sends the Pending response which contains 
 * matched data set. Then success response is sent by SCP.
 * This operation is part of Synchronous mode request handling.  
 * Once the DIMSE response is received by the SubstanceAdministrationInfoQrySCU 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 C-Find operation is complete,we can create another association
 * and send more requests. 
 * Also it is possible to create multiple C-Find-RQs and send them one by one on the same Association.
 */
public class SubstanceAdministrationInfoQry_SCU 
{
	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'.
		//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 object of TestCStoreSCU and Start CStore SCU.
		 */
		SubstanceAdministrationInfoQry_SCU objSubstanceAdministrationInfoQry_SCUTest = new SubstanceAdministrationInfoQry_SCU();

		objSubstanceAdministrationInfoQry_SCUTest.start();
	}

	/**
	 * This method starts C-Find SCU .
	 */
	public void start()
	{
		//Current SCU Session
		SCUSession objSession = null;

		try
		{
			//create SCU session.
			objSession = new SCUSession();
			
			/*
			 * Initializes the service types and populates the default association
			 */
			EnumServiceType[] arrenumServiceType = new EnumServiceType[1];
			arrenumServiceType[0] = EnumServiceType.CFIND_SUBSTANCEADMINISTRATION;
			DefaultAssociation objDefaultAssociation = new DefaultAssociation("SDK");
			objDefaultAssociation.loadAssociation(arrenumServiceType);

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

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

			//Create CFind SCU object using the current SCU Session.
			CFindSCU objCFindSCU = new CFindSCU(objSession);

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

				//set the data set on C-Find RQ. The Data set contains the query attributes
				//and the key attribute.
				IDataSet objIDataSet = getDataSet();

				//Create Default CFind 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.
				CFindRQ objCFindRQ = CFindRQ.getDefaultRQ(DicomConstants.DCM_SUBSTANCE_APPROVAL_QUERY_SOP_INSTANCE, objIDataSet);

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

				//Send the C-Find-RQ and wait for a C-Find-RSP.
				//This method exits once the response is received. This response is 
				//added in the response collection maintained by the CFindSCU which
				//can be retrieved. This method returns 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.)
				//The matched attributes are sent in the pending response data set and then the success response is sent
				//No of pending response is the no of matches found.
				if(objCFindSCU.sendMessage(objCFindRQ))
				{
					System.out.println("CFind Operation performed");
					ISingleCollection<DicomMessage> objSingleCollection = objCFindSCU.getDIMSEResponse();
					System.out.println("Size of collection :: " + objSingleCollection.size());

					/*
					 * This will get the pending response from the Dicom Message and displays it.
					 */
					for(DicomMessage objDicomMessage : objSingleCollection)
					{
						CFindRSP objCFindRSP = new CFindRSP(objDicomMessage);
						System.out.println("C-Find Response Status is  :" + objCFindRSP.getStatus() );
						IDataSet objIDataSet2 = objDicomMessage.getDataSet();
						if(objIDataSet2 != null)
						{
							System.out.println("*********************************************");
							display(objIDataSet2);
							System.out.println("*********************************************");
						}
					}
				}
				else
					System.out.println("C-Find operation failed.");

				//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("Association is released");
					//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-Find-RQs and send them one by one.
					objSession.close();
				}

				//In case an ABORT is received from SCP during the C-Store 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();
			objSession.close();
		}
	}

	static int i = 0;

	/*
	 * Displays the DataElements of Dataset
	 */
	private void display(IDataSet objIDataSet)
	{
		ICollectionIterator<IDataElement> objIDataSetIterator = objIDataSet.iterator();

		System.out.println("Tag     Value");
		while(objIDataSetIterator.hasNext())
		{
			IDataElement objDataElement = objIDataSetIterator.next();				

			if(!(objDataElement.getDicomValue() instanceof SQ))
			{

				System.out.println(objDataElement.getTag().getGroupNumber()+"    "+
						objDataElement.getTag().getElementNumber()+"    "+
						objDataElement.getDicomValue().toString());
			}
			else  
			{
				displaySequence((SQ)objDataElement.getDicomValue(),"> ");					
			}
		}

	}

	/*
	 * Displays the Dicom Data SQ.
	 */
	private void displaySequence(SQ objSQDataElement,String ss)
	{
		ICollectionIterator<IItem> objSQItemIterator = objSQDataElement.iterator();
		int i = 1;
		while(objSQItemIterator.hasNext())
		{
			System.out.println("ITEM :"+ i++ );
			IItem objItem = objSQItemIterator.next();
			ICollectionIterator<IDataElement> objDataElementIterator = objItem.iterator();
			while(objDataElementIterator.hasNext())
			{
				IDataElement objDataElement = objDataElementIterator.next();

				if(!(objDataElement.getDicomValue() instanceof SQ))
				{
					System.out.println(ss +objDataElement.getTag().getGroupNumber()+"    "+
							objDataElement.getTag().getElementNumber()+"    "+
							objDataElement.getDicomValue().toString());						 
				}
				else
				{
					displaySequence((SQ)objDataElement.getDicomValue(),ss+ss);
				}	 
			}
		}
	}

	/*
	 * Get the SubstanceAdministrationInfoQry Data Set. The SubstanceAdministrationInfoQry data set contains the data elements which needs to be searched.
	 */
	public IDataSet getDataSet()
	{
		IDataSet objIDataSet = new DataSet();
		IDictionaryReader objDictionaryReader = objIDataSet.getDictionaryReader();
		//ITransferSyntax objTS = objIDataSet.getTransferSyntax();

		objIDataSet.addDataElement(getDataElement(0x0000,0x0002, null, objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0000,0x0120, null, objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0000,0x0800, null, objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0010,0x0010, null, objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0010,0x0020, "XA134", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0010,0x0010, null, objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0010,0x0030, null, objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0044,0x0001, null, objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0038,0x0010, null, objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0044,0x0002, null, objDictionaryReader));

		
		return objIDataSet;
	}
	/*
	 * Get the data element belonging to the information provided
	 */
	private IDataElement getDataElement(int GroupNo,int ElementNo,Object objVal,IDictionaryReader objDictionaryReader)
	{
		IDataElement objIDataElement = new ImplicitDE(GroupNo, ElementNo,objVal,objDictionaryReader);
		return objIDataElement;
	}
}
