/*******************************************************************************
 *  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.storagecommitment.testcases.defaultscp;
import java.io.IOException;


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.services.dicomnetcommons.EnumServiceType;
import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.DicomMessage;
import cdac.medinfo.sdk.dcm30_04.services.scp.commons.ClientSession;
import cdac.medinfo.sdk.dcm30_04.services.scp.commons.ProcessHandler;
import cdac.medinfo.sdk.dcm30_04.services.scp.commons.SCPSession;
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 Sample Code works as N-Event Report SCP .
 * This sample test case extends ProcessHandler class which is default implementation 
 * of SDK to process all kinds of Association and Service Request.
 * Once the required parameters are given to the ProcessHandler and is started , 
 * it is capable of process all association and service requests and sending their response .
 * User of Storage Commitment SCU should start this server after sending Storage Commitment Request to 
 * receive N-Event Report Information.
 * The IP and port on which this server is started should also be provided to Storage Commitment SCP.
 */
public class NEventReport_SCP
{
	public static void main(String[] args) throws IOException
	{
		DicomConfig objDicomConfig = DicomConfig.createInstance();

		//Enables logging mode in SDK. In SEVERE logging level
		//Exceptions are logged.
		objDicomConfig.enableLogging(EnumLoggingLevel.SEVERE, "C:\\DCM_Logs");

		/*
		 * Creates StorageCommitmentHandler.
		 */
		NEventReportSCPHandler scp = new NEventReportSCPHandler();
		scp.doEventReportHandling();
	}
}

/**
 * This is the default implementation of the sample test code for NEvent Report Services.
 * This sample codes is to show the handling of connection, association and service request 
 * by the default Process Handler Implementation of the SDK.
 * The Sample Test code should be extended from the ProcessHandler class of SDK for DICOM.
 * Then all the connection , association and service requests are handled by the deafult implementaion
 * of the SDK.
 */
class NEventReportSCPHandler extends ProcessHandler
{
	public void doEventReportHandling() throws IOException
	{
		//Create SCP Session 
		SCPSession session = new SCPSession();

		/*
		 * Initializing selected services on SCPSession.
		 * This selection customises assocaition loading process where the association context related to
		 * selected services will only be loaded for negotiation purpose.
		 */
		EnumServiceType []arrenumServiceType = new EnumServiceType[1];
		arrenumServiceType[0] = EnumServiceType.NEVENTREPORT_STORAGE_COMMITMENT;
		session.selectServices(arrenumServiceType);

		/*
		 * Set EnumCommandFiled on ProcessHandler. The procesHandler will process the services whose
		 * command field is set in Processhandler. For the request of other services the process handler
		 * will generate Abort.
		 */
		ISingleCollection<EnumCommandField> objEnumCommandField = new SingleCollection<EnumCommandField>();
		objEnumCommandField.add(EnumCommandField.N_EVENT_REPORT_RQ);
		setEnumCommandField(objEnumCommandField);


		//Set Process Handler as the SCP TestCode
		session.setIProcessHandler(this);
		
		/*
		 * 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.
		 */ 
		//session.setTimeOut(5000);

		//Start the Session
		session.start("SDK",9999);
	}

	/**
	 * This function is called when association request is recieved.
	 * It call process handler onAssociateReceive to process Association Request.
	 */
	public void onAssociateReceive(ClientSession objClientSession)
	{
		System.out.println("Association Request Received");
		super.onAssociateReceive(objClientSession);
	}

	/**
	 * This function is called when service request is recieved.
	 * It call process handler onServiceRequest to process Service Request.
	 */
	public void onServiceRequest(ClientSession objClientSession) throws IOException
	{
		System.out.println("Service Request Received");
		super.onServiceRequest(objClientSession);
		DicomMessage objDicomMessage = objClientSession.getDicomMessage();
		IDataSet objDataSet = objDicomMessage.getDataSet();
		display(objDataSet);
	}

	/*
	 * This function displays DataSet.
	 */
	@SuppressWarnings("unchecked")
	private void display(IDataSet objIDataSet)
	{
		System.out.println("\nFailed SOP Sequence : \n");
		ISingleCollection<IItem> objSQFailedSOPSequenceItem = (ISingleCollection<IItem>)(objIDataSet.getValue(0x0008, 0x1198));
		ICollectionIterator<IItem> objSQItemIterator = objSQFailedSOPSequenceItem.iterator();
		displayRes(objSQItemIterator);

		System.out.println("\nReferenced SOP Sequence : \n");
		ISingleCollection<IItem> objSQReferencedSOPSequenceItem = (ISingleCollection<IItem>)(objIDataSet.getValue(0x0008, 0x1199));
		ICollectionIterator<IItem> objSQItemIterator1 = objSQReferencedSOPSequenceItem.iterator();
		displayRes(objSQItemIterator1);
	}

	/*
	 * This function displays items of sequence.
	 */
	private void displayRes(ICollectionIterator<IItem> objSQItemIterator)
	{
		while(objSQItemIterator.hasNext())
		{
			IItem objItem = objSQItemIterator.next();
			ICollectionIterator<IDataElement> objDataElementIterator = objItem.iterator();
			while(objDataElementIterator.hasNext())
			{
				IDataElement objDataElement = objDataElementIterator.next();
				System.out.println("> "+objDataElement.getTag().getGroupNumber()+"    "+
						objDataElement.getTag().getElementNumber()+"    "+
						objDataElement.getDicomValue().toString());						 
			}
		}	
	}
}

