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


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.EnumSOPClassUIDs;

import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.DicomMessage;
import cdac.medinfo.sdk.dcm30_04.services.substanceadministration.scu.SubstanceAdministrationInfoQrySCU;
import cdac.medinfo.sdk.dcm30_04.utils.DicomConfig;
import cdac.medinfo.sdk.dcm30_04.utils.ICollectionIterator;
import cdac.medinfo.sdk.dcm30_04.utils.ISingleCollection;
import cdac.medinfo.sdk.dcm30_04.utils.SingleCollection;

/**
 * This class tests a Stand Alone SubstanceAdministrationInfoQry SCU.
 * "Stand Alone" means that the User is required to write a minimal set of code to actually send a 
 * CStore Request. Once the required parameters are given to the CStoreSCU object it is 
 * capable of making a connection to the SCP, establishing association, sending the CStore Request and receiving the 
 * DIMSE Response for the same. If User wants to handle the request sending scenarios by his/her code 
 * then please refer to sample code "TestSubstanceAdministrationInfoQrySCU.java". 
 */
public class SubstanceAdministrationInfoQry_SCU_Stanalone 
{
	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'.
			//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 TestStandaloneCStoreSCU.
			 */
			SubstanceAdministrationInfoQry_SCU_Stanalone objTestStanaloneSubstanceAdministrationInfoQry_SCU = new SubstanceAdministrationInfoQry_SCU_Stanalone();
			objTestStanaloneSubstanceAdministrationInfoQry_SCU.doSubstanceAdministrationInfoQry();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	/*
	 * This function starts there SubstanceAdministrationInfoQry operation,
	 */
	public void doSubstanceAdministrationInfoQry()throws IOException
	{
		/* 
		 * Creates SCU with specified destination .
		 */
		InetSocketAddress addr = new InetSocketAddress("localhost",9000);
		SubstanceAdministrationInfoQrySCU objSubstanceAdministrationInfoQrySCU = new SubstanceAdministrationInfoQrySCU(addr);
		IDataSet objIDataSet=getDataSet();
		/*
		 * Create Data Set collection.
		 */
		ISingleCollection<IDataSet> objIDataSetCollection = new SingleCollection<IDataSet>();
		objIDataSetCollection.add(objIDataSet);

		/*
		 * Send the C-Find DataSet with Affected SOP class UID of SubstanceAdministrationInfoQry
		 */
		objSubstanceAdministrationInfoQrySCU.send("SDK","SDK",EnumSOPClassUIDs.DCM_PRODUCT_CHARACTERISTICS_QUERY_SOP_CLASS.getValue(), objIDataSetCollection);

		/*
		 * After the request is send user can get the response collection.
		 */

		ISingleCollection<DicomMessage> objSingleCollection = objSubstanceAdministrationInfoQrySCU.getDIMSEResponse();
		System.out.println("SubstanceAdministrationInfoQry operation Response Collection Size :: " + objSingleCollection.size());

		/*
		 * This will get the pending response from the Dicom Message and displays it.
		 */
		for(DicomMessage objDicomMessage : objSingleCollection)
		{
			IDataSet objIDataSet2 = objDicomMessage.getDataSet();
			if(objIDataSet2 != null)
			{
				System.out.println("*********************************************");
				display(objIDataSet2);
				System.out.println("*********************************************");
			}
		}
	}

	/*
	 * 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(),"> ");					
			}
		}

	}

	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, "33221", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0010,0x0010, null, objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0010,0x0030, null, objDictionaryReader));
		return objIDataSet;
	}

	/*
	 * This function create the data element from the information provided.
	 */
	private IDataElement getDataElement(int GroupNo,int ElementNo,Object objVal,IDictionaryReader objDictionaryReader)
	{
		IDataElement objIDataElement = new ImplicitDE(GroupNo, ElementNo,objVal,objDictionaryReader);
		return objIDataElement;
	}
}
