/*******************************************************************************
 *  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.rtmachineverificationservice.testcases.nset;

import cdac.medinfo.sdk.dcm30_04.baselibs.ApplicatorSequence;
import cdac.medinfo.sdk.dcm30_04.baselibs.ApplicatorSequenceItem;
import cdac.medinfo.sdk.dcm30_04.baselibs.BeamLimitingDevicePositionSequence;
import cdac.medinfo.sdk.dcm30_04.baselibs.BeamLimitingDevicePositionSequenceItem;
import cdac.medinfo.sdk.dcm30_04.baselibs.ConventionalControlPointVerificationSequence;
import cdac.medinfo.sdk.dcm30_04.baselibs.ConventionalControlPointVerificationSequenceItem;
import cdac.medinfo.sdk.dcm30_04.baselibs.ConventionalMachineVerificationSequence;
import cdac.medinfo.sdk.dcm30_04.baselibs.ConventionalMachineVerificationSequenceItem;
import cdac.medinfo.sdk.dcm30_04.baselibs.DataSet;
import cdac.medinfo.sdk.dcm30_04.baselibs.GeneralMachineVerificationSequence;
import cdac.medinfo.sdk.dcm30_04.baselibs.GeneralMachineVerificationSequenceItem;
import cdac.medinfo.sdk.dcm30_04.baselibs.RecordedBlockSequence;
import cdac.medinfo.sdk.dcm30_04.baselibs.RecordedBlockSequenceItem;
import cdac.medinfo.sdk.dcm30_04.baselibs.RecordedCompensatorSequence;
import cdac.medinfo.sdk.dcm30_04.baselibs.RecordedCompensatorSequenceItem;
import cdac.medinfo.sdk.dcm30_04.baselibs.ReferencedBolusSequence;
import cdac.medinfo.sdk.dcm30_04.baselibs.ReferencedBolusSequenceItem;
import cdac.medinfo.sdk.dcm30_04.baselibs.WedgePositionSequence;
import cdac.medinfo.sdk.dcm30_04.baselibs.WedgePositionSequenceItem;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IDataSet;
import cdac.medinfo.sdk.dcm30_04.dicommodel.modules.RTConventionalMachineVerificationModule;
import cdac.medinfo.sdk.dcm30_04.dicommodel.modules.RTGeneralMachineVerificationModule;
import cdac.medinfo.sdk.dcm30_04.dicommodel.rt.RTConventionalMachineVerificationIOD;
import cdac.medinfo.sdk.dcm30_04.enums.EnumApplicatorType;
import cdac.medinfo.sdk.dcm30_04.enums.EnumGantryRotationDirection;
import cdac.medinfo.sdk.dcm30_04.enums.EnumLoggingLevel;
import cdac.medinfo.sdk.dcm30_04.enums.EnumPDUType;
import cdac.medinfo.sdk.dcm30_04.enums.EnumRTBeamLimitingDeviceType;
import cdac.medinfo.sdk.dcm30_04.enums.EnumRadiationType;
import cdac.medinfo.sdk.dcm30_04.enums.EnumSOPClassUIDs;
import cdac.medinfo.sdk.dcm30_04.enums.EnumWedgePosition;

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.nset.commons.NSetRQ;
import cdac.medinfo.sdk.dcm30_04.services.rtmachineverificationservice.scu.RTMachineVerification_SCU;
import cdac.medinfo.sdk.dcm30_04.services.scu.commons.SCUSession;
import cdac.medinfo.sdk.dcm30_04.utils.DicomConfig;

/**
/**
 * This sample code specifies the role of RT Conventional Machine Verification SCU for N-Set Service.
 * It uses RT Conventional Machine Verification SCU to send the request to SCP.
 * 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.
 * 
 * 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 Services Type in loadAssociation method of Default association.
 * 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 respective SCU object to send the service Request to the SCP. Currently the "sendMessage" method 
 * of the respective SCU would wait after sending the service DIMSE-RQ until a suitable DIMSE-RSP is received. 
 * This operation is part of Synchronous mode request handling.  
 * Once the DIMSE response is received by the SCU 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 service operation is complete,we can create another association
 * and send more requests. 
 * Also it is possible to create multiple service requests and send them one by one on the same Association.
 */
public class RTConventionalMachineVerification_TestSCU 
{
	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");

		/*
		 * Creates instance of TestRT Conventional Machine Verification_SCU
		 */
		RTConventionalMachineVerification_TestSCU objTestRTMachineVerification_SCU = new RTConventionalMachineVerification_TestSCU();

		/*
		 * Performs operation of RT Conventional Machine Verification Services 
		 */
		objTestRTMachineVerification_SCU.dostart();
	}

	/**
	 * This function performs the operation for N-Set Service of RT Conventional Machine Verification.
	 * RT Conventional Machine Verification operation involves following steps :-
	 * 1. Establish the connection with SCP
	 * 2. Establish the association with SCP
	 * 3. Initializes the SCU for corresponding N-Service and performs the operation using service request
	 * 4. Releases the association after successful processing of service request
	 * 5. Closes the connection with SCP. 
	 */
	public void dostart()
	{
		try
		{

			//Create SCUSession object
			SCUSession 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);
			
			//Start SCU Session by providing the IP address and Port of SCP.
			objSession.start("localhost", 9000);

			/*
			 * *************************************************************************
			 * This block of code initializes the DefaultAssociation information
			 * Using the DefaultAssociation it generates the Association Request and 
			 * creates association  with SCP.
			 * *************************************************************************
			 */

			// Initializes the service types and populates the Default Association
			EnumServiceType[] arrenumServiceType = new EnumServiceType[1];
			
			arrenumServiceType[0] = EnumServiceType.NSET_RT_CONVENTIONAL_MACHINE_VERIFICATION;
			
			DefaultAssociation objDefaultAssociation = new DefaultAssociation("SDK");
			objDefaultAssociation.loadAssociation(arrenumServiceType);

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

			//Send the Association Request
			if(objSession.sendAssociationMessage(objAssociateRQ))
			{	
				//When association is successfully established the "objSession.sendAssociationMessage()" method returns true.
				System.out.println("Association established");


				//Create  RT Machine Verification SCU object using the current SCU Session.
				RTMachineVerification_SCU objRTMachineVerification_SCU = new RTMachineVerification_SCU(objSession);
			
				
				/*
				 * *************************************************************************
				 * This block of code initializes the NSet RQ and sends it to SCP using RT Conventional Machine Verification_SCU.
				 * It performs updation operation for RT Conventional Machine Verification SOP Instance.
				 * *************************************************************************
				 */
				
				//Generates Modified Dataset for RT Conventional Machine Verification 
				IDataSet objModifiedRTConventionalMachineVerificationDataSet = getModifiedRTConventionalMachineVerificationIOD();
				//Initializing NSet RQ for same SOP Instance
				NSetRQ objNSetRQ = NSetRQ.getDefaultRQ(EnumSOPClassUIDs.DCM_RT_CONVENTIONAL_MACHINE_VERIFICATION.getValue(),"1.2.840.10008.5.1.2.69.1", objModifiedRTConventionalMachineVerificationDataSet);
				System.out.println("RT Conventional Machine Verification Request For N-Set RQ Initialized");

				//sending RQ to SCP
				if(objRTMachineVerification_SCU.sendMessage(objNSetRQ)) //sending request
					System.out.println("RT Conventional Machine Verification Instance Updation Operation performed");
				else
					System.out.println("RT Conventional Machine Verification Instance Updation 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))
				{

					objSession.close();
				}

				//In case an ABORT is received from SCP during the RT Conventional Machine Verification 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();
		}
	}



	/**
	 * Populates the DataSet with modified values for RT Conventional Machine Verification.
	 * It populates the Dataset manually using some default values of Data elements for RT Conventional Machine Verification.
	 * This Dataset can be generated using some file also.
	 * @return objIDataSet instance of IDataSet.
	 */
	private IDataSet getModifiedRTConventionalMachineVerificationIOD()
	{
		IDataSet objIDataSet = new DataSet();
		objIDataSet.getDictionaryReader();
		objIDataSet.getTransferSyntax();

		
		RTConventionalMachineVerificationIOD objRTConventionalMachineVerificationIOD=new RTConventionalMachineVerificationIOD();		
		
		//RT General Machine Verification Module
		RTGeneralMachineVerificationModule objRTGeneralMachineVerificationModule=objRTConventionalMachineVerificationIOD.getRTGeneralMachineVerificationModule();		
		
		//RT Conventional Machine Verification Module
		RTConventionalMachineVerificationModule objRTConventionalMachineVerificationModule=objRTConventionalMachineVerificationIOD.getRTConventionalMachineVerificationModule();
	
		//General Machine Verification Sequence
		GeneralMachineVerificationSequence objGeneralMachineVerificationSequence=objRTGeneralMachineVerificationModule.getGeneralMachineVerificationSequence();
		GeneralMachineVerificationSequenceItem objGeneralMachineVerificationSequenceItem=objGeneralMachineVerificationSequence.getNewItem();
		objGeneralMachineVerificationSequenceItem.setSpecifiedTreatmentTime("300");		
		objGeneralMachineVerificationSequenceItem.setTreatmentMachineName("Test123");
		objGeneralMachineVerificationSequenceItem.setRadiationType(EnumRadiationType.PHOTON);
		objGeneralMachineVerificationSequenceItem.setNumberOfWedges("20");
		objGeneralMachineVerificationSequenceItem.setNumberOfBlocks("22");
		objGeneralMachineVerificationSequenceItem.setNumberOfCompensators("24");
		objGeneralMachineVerificationSequenceItem.setNumberOfBoli("26");		
		objGeneralMachineVerificationSequenceItem.setNumberOfControlPoints("1");
		objGeneralMachineVerificationSequenceItem.setReferencedBeamNumber("28");
		
		//Recorded Compensator Sequence
		RecordedCompensatorSequence objRecordedCompensatorSequence=objGeneralMachineVerificationSequenceItem.getRecordedCompensatorSequence();
		RecordedCompensatorSequenceItem objRecordedCompensatorSequenceItem=objRecordedCompensatorSequence.getNewItem();
		objRecordedCompensatorSequenceItem.setReferencedCompensatorNumber("101");
		objRecordedCompensatorSequence.addItem(objRecordedCompensatorSequenceItem);
		
		//Recorded Block Sequence
		RecordedBlockSequence objRecordedBlockSequence=objGeneralMachineVerificationSequenceItem.getRecordedBlockSequence();
		RecordedBlockSequenceItem objRecordedBlockSequenceItem=objRecordedBlockSequence.getNewItem();
		objRecordedBlockSequenceItem.setReferencedBlockNumber("33");
		objRecordedBlockSequence.addItem(objRecordedBlockSequenceItem);
		
		
		//Applicator Sequence
		ApplicatorSequence objApplicatorSequence=objGeneralMachineVerificationSequenceItem.getApplicatorSequence();
		ApplicatorSequenceItem objApplicatorSequenceItem=objApplicatorSequence.getNewItem();
		objApplicatorSequenceItem.setApplicatorType(EnumApplicatorType.ELECTRON_RECTANGULAR);
		objApplicatorSequence.addItem(objApplicatorSequenceItem);
				
		//Referenced Bolus Sequence
		ReferencedBolusSequence objReferencedBolusSequence=objGeneralMachineVerificationSequenceItem.getReferencedBolusSequence();
		ReferencedBolusSequenceItem objReferencedBolusSequenceItem=objReferencedBolusSequence.getNewItem();
		objReferencedBolusSequenceItem.setReferencedROINumber("101010");
		objReferencedBolusSequence.addItem(objReferencedBolusSequenceItem);		
		
		objGeneralMachineVerificationSequence.addItem(objGeneralMachineVerificationSequenceItem);
		
	
		//Conventional Machine Verification Sequence
		ConventionalMachineVerificationSequence objConventionalMachineVerificationSequence=objRTConventionalMachineVerificationModule.getConventionalMachineVerificationSequence();
		ConventionalMachineVerificationSequenceItem objConventionalMachineVerificationSequenceItem=objConventionalMachineVerificationSequence.getNewItem();
		
		
		//ConventionalControlPointVerificationSequence
		ConventionalControlPointVerificationSequence objConventionalControlPointVerificationSequence=objConventionalMachineVerificationSequenceItem.getConventionalControlPointVerificationSequence();
		ConventionalControlPointVerificationSequenceItem objConventionalControlPointVerificationSequenceItem=objConventionalControlPointVerificationSequence.getNewItem();
		objConventionalControlPointVerificationSequenceItem.setNominalBeamEnergy("250");
		objConventionalControlPointVerificationSequenceItem.setDoseRateSet("50");
		objConventionalControlPointVerificationSequenceItem.setGantryAngle("45");
		objConventionalControlPointVerificationSequenceItem.setGantryRotationDirection(EnumGantryRotationDirection.NO_ROTATION);
		objConventionalControlPointVerificationSequenceItem.setReferencedControlPointIndex("66");
		objConventionalControlPointVerificationSequence.addItem(objConventionalControlPointVerificationSequenceItem);	
		
		//WedgePositionSequence
		WedgePositionSequence objWedgePositionSequence=objConventionalControlPointVerificationSequenceItem.getWedgePositionSequence();
		WedgePositionSequenceItem objWedgePositionSequenceItem=objWedgePositionSequence.getNewItem();
		objWedgePositionSequenceItem.setWedgePosition(EnumWedgePosition.IN);
		objWedgePositionSequenceItem.setReferencedWedgeNumber("3");
		objWedgePositionSequence.addItem(objWedgePositionSequenceItem);
		
		//BeamLimitingDevicePositionSequence
		BeamLimitingDevicePositionSequence objBeamLimitingDevicePositionSequence=objConventionalControlPointVerificationSequenceItem.getBeamLimitingDevicePositionSequence();
		BeamLimitingDevicePositionSequenceItem objBeamLimitingDevicePositionSequenceItem=objBeamLimitingDevicePositionSequence.getNewItem();
		objBeamLimitingDevicePositionSequenceItem.setRTBeamLimitingDeviceType(EnumRTBeamLimitingDeviceType.SYMMETRIC_IEC_X_DIRECTION);
		String[]arr={"101","102"};
		objBeamLimitingDevicePositionSequenceItem.setLeaf_JawPositions(arr);		
		objBeamLimitingDevicePositionSequence.addItem(objBeamLimitingDevicePositionSequenceItem);
		
		
		objConventionalMachineVerificationSequence.addItem(objConventionalMachineVerificationSequenceItem);
		
		objRTConventionalMachineVerificationIOD.getSOPCommonModule().setSOPInstanceUID("1.2.840.10008.5.1.2.69.1");
		
		return  objRTConventionalMachineVerificationIOD.getDataSet();
		
	}
}
