/*******************************************************************************
 *  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.DisplaySystemManagement.testcases.scu;

import java.io.IOException;
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.IItem;
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.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.dicomnetcommons.EnumServiceType;
import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.DicomMessage;
import cdac.medinfo.sdk.dcm30_04.services.displaysystemmanagement.scu.DisplaySystemSCU;
import cdac.medinfo.sdk.dcm30_04.services.nget.commons.NGetRQ;
import cdac.medinfo.sdk.dcm30_04.services.nget.commons.NGetRSP;
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.DicomConstants;
import cdac.medinfo.sdk.dcm30_04.utils.ICollectionIterator;


/**
 * This class tests a Stand Alone Display System SCU.
 * "Stand Alone" means that the User is required to write a minimal set of code to actually send a 
 * NGet Request. Once the required parameters are given to the NGetSCU object it is 
 * capable of making a connection to the SCP, establishing association, sending the NGet 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 "DisplaySystemSCU.java". 
 */
public class Display_System_SCU_Standalone 
{
	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 Display_System_SCU_Stanalone.
			 */
			Display_System_SCU_Standalone objDisplay_System_SCU_Stanalone = new Display_System_SCU_Standalone();
			objDisplay_System_SCU_Stanalone.doDisplaySystemInfoQry();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	/*
	 * This function starts the DisplaySystemInfoQry operation,
	 */
	public void doDisplaySystemInfoQry()throws IOException
	{

		//Create SCUSession object
		SCUSession objSession = new SCUSession();
		objSession.start("localhost", 9000);
		/*
		 * Initializes the service types and populates the default association
		 */
		EnumServiceType[] arrenumServiceType = new EnumServiceType[1];
		arrenumServiceType[0] = EnumServiceType.NGET_DISPLAY_SYSTEM_MANAGEMENT;
		DefaultAssociation objDefaultAssociation = new DefaultAssociation("SDK");
		objDefaultAssociation.loadAssociation(arrenumServiceType);
		
		//Create Association RQ
		AssociateRQ objAssociateRQ = objDefaultAssociation.getAssociationRQ("SDK");
		
		if(objSession.sendAssociationMessage(objAssociateRQ))
		{
		DisplaySystemSCU objDisplaySystemSCU = new DisplaySystemSCU(objSession);

		//Initializing NGet RQ
		NGetRQ objNGetRQ = NGetRQ.getDefaultRQ(EnumSOPClassUIDs.DISPLAYSYSTEMIOD.getValue(), DicomConstants.DCM_DISPLAY_SYSTEM_SOP_INSTANCE, null);
		System.out.println("N-Get Request for Display System  initialized");

		//sending RQ to SCP
		if(objDisplaySystemSCU.sendMessage(objNGetRQ)) 
			System.out.println("Display System  Operation performed");
		else
			System.out.println("Display System Operation failed");

		//Retrieves Dataset from NGet RSP and displays it.After retrieval it removes that response from response collection.
		
		for(DicomMessage objDicomMessage : objDisplaySystemSCU.getDIMSEResponse())
		{
			if(objDicomMessage.getCommandType() == EnumCommandField.N_GET_RSP)
			{
				NGetRSP objNGetRSP = new NGetRSP(objDicomMessage);
				IDataSet objRstDataSet = objNGetRSP.getDataSet();
				if(objRstDataSet != null)
				{
					System.out.println("Retrieved Dataset information ---- ");
					display(objRstDataSet);
				}
				objDisplaySystemSCU.getDIMSEResponse().remove(objDicomMessage);
				break;
			}
		}
		//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 N-Get-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");
		}
	}

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