/*******************************************************************************
 *  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.implanttemplate.testcases.CStorecu;

import cdac.medinfo.sdk.dcm30_04.baselibs.DataSet;
import cdac.medinfo.sdk.dcm30_04.baselibs.DicomV3Factory;
import cdac.medinfo.sdk.dcm30_04.baselibs.ImplicitDE;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IDataElement;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IDataSet;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IDataTypeSQ;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IDictionaryReader;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IItem;
import cdac.medinfo.sdk.dcm30_04.commoninterface.ITransferSyntax;
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.cstore.commons.CStoreRQ;
import cdac.medinfo.sdk.dcm30_04.services.cstore.commons.CStoreRSP;
import cdac.medinfo.sdk.dcm30_04.services.cstore.scu.CStoreSCU;
import cdac.medinfo.sdk.dcm30_04.services.dicomnetcommons.EnumServiceType;
import cdac.medinfo.sdk.dcm30_04.services.scu.commons.SCUSession;
import cdac.medinfo.sdk.dcm30_04.utils.DicomConfig;

/**
 * This class is implemented to test the Implant Template's C-Store SCU.
 * 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 Service Type in loadAssociation method of Default association. For e.g. here EnumServiceType.CSTORE
 * should be specified to load Association for C-Store Services. The association request for C-Store 
 * 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 CStoreSCU object to send the C-Store Request to the respective SCP. Currently the "sendMessage" method 
 * of the CStoreSCU would wait after sending the C-Store-RQ until a suitable DIMSE response is received. 
 * This operation is part of Synchronous mode request handling.  
 * Once the DIMSE response is received by the CStoreSCU 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-Store operation is complete,we can create another association
 * and send more requests. 
 * Also it is possible to create multiple C-Store-RQs and send them one by one on the same Association.
 */
public class ImplantTemplate_SCU 
{

	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 ImplantTemplate_SCU
		 */
		ImplantTemplate_SCU objTestImplantTemplateSCU = new ImplantTemplate_SCU();

		/*
		 * Starts Implant Template SCU.
		 */
		objTestImplantTemplateSCU.start();
	}
	/*
	 * This function populates the data set. ImplantTemplate service query on instance populated.
	 */
	public IDataSet populateDataset()
	{
		IDataSet objIDataSet = new DataSet();
		IDictionaryReader objDictionaryReader = objIDataSet.getDictionaryReader();
		ITransferSyntax objTS = objIDataSet.getTransferSyntax();
		
		objIDataSet.addDataElement(getDataElement(0x0000,0x0002, EnumSOPClassUIDs.GENERICIMPLANTTEMPLATEIOD.getValue(), objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0000,0x0120,  (short)10, objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0000,0x0800, (short)12, objDictionaryReader));
		
		objIDataSet.addDataElement(getDataElement(0x0008,0x0016, "1.2.840.10008.5.1.4.43.1", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0008,0x0018, "1.2.3.4.5.6.7.1.2", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0008,0x0070, "ACME", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0022,0x1095, "MONO_CUP", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0068,0x6210, "MEDIUM", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0022,0x1097, "ACME_MCP_M", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0068,0x6226, "20021114124623", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0068,0x6221,  "1", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0068,0x6223, "ORIGINAL", objDictionaryReader));

		
		
		IDataTypeSQ objImplantTargetAnatomySequence = getSQ(0x0068,0x6230,objTS);
		IItem objImplantTargetAnatomySequenceItem = objImplantTargetAnatomySequence.getNewItem();
		
		objImplantTargetAnatomySequenceItem.addDataElement(getDataElement(0x0008,0x0100, "T-15710", objDictionaryReader));
		objImplantTargetAnatomySequenceItem.addDataElement(getDataElement(0x0008,0x0102, "SRT", objDictionaryReader));
		objImplantTargetAnatomySequenceItem.addDataElement(getDataElement(0x0008,0x0104, "Hip Joint", objDictionaryReader));		
		objImplantTargetAnatomySequence.addItem(objImplantTargetAnatomySequenceItem);
		objIDataSet.addDataElement(getDataElement(0x0068,0x6230,objImplantTargetAnatomySequence.getValue(), objDictionaryReader));
		
		
		objIDataSet.addDataElement(getDataElement(0x0020,0x0052, "1.2.3.4.5.6.7.1.2", objDictionaryReader));

		IDataTypeSQ objMaterialCodeSequence = getSQ(0x0068,0x63A0,objTS);
		IItem objMaterialCodeSequenceItem = objMaterialCodeSequence.getNewItem();
		objMaterialCodeSequenceItem.addDataElement(getDataElement(0x0008,0x0102, "SRT", objDictionaryReader));
		objMaterialCodeSequenceItem.addDataElement(getDataElement(0x0008,0x0100, "F-61207", objDictionaryReader));
		objMaterialCodeSequenceItem.addDataElement(getDataElement(0x0008,0x0104, "Stainless Steel Material", objDictionaryReader));
		objMaterialCodeSequence.addItem(objMaterialCodeSequenceItem);
		objIDataSet.addDataElement(getDataElement(0x0068,0x63A0,objMaterialCodeSequence.getValue(), objDictionaryReader));
		
		IDataTypeSQ objMatingFeatureSetsSequence = getSQ(0x0068,0x63B0,objTS);
		IItem objMatingFeatureSetsSequenceItem = objMaterialCodeSequence.getNewItem();
		objMatingFeatureSetsSequenceItem.addDataElement(getDataElement(0x0068,0x63C0, (short)1, objDictionaryReader));
		objMatingFeatureSetsSequenceItem.addDataElement(getDataElement(0x0068,0x63D0, "Hip Joint Mating Feature", objDictionaryReader));
		objMatingFeatureSetsSequence.addItem(objMatingFeatureSetsSequenceItem);
		objIDataSet.addDataElement(getDataElement(0x0068,0x63B0,objMatingFeatureSetsSequence.getValue(), 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;
	}
	/*
	 * This function gets the sequence belonging to group no and element number specified.
	 */
	private IDataTypeSQ getSQ(int GroupNo,int ElementNo , ITransferSyntax objTS)
	{
		return DicomV3Factory.createInstance().createSequence(GroupNo, ElementNo, objTS);
	}

	/**
	 * This function performs the CStore operation.
	 */
	public void start()
	{
		try
		{
			/*
			 * *************************************************************************
			 * This block of code performs the connection process with SCP.
			 * It creates the SCUSession and connects with SCP using this session.
			 * *************************************************************************
			 */
			//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 loads the Default Association
			EnumServiceType[] arrenumServiceType = new EnumServiceType[1];
			arrenumServiceType[0] = EnumServiceType.CSTORE_IMPLANTTEMPLATE;
			DefaultAssociation objDefaultAssociation = new DefaultAssociation("SDK");
			objDefaultAssociation.loadAssociation(arrenumServiceType);

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

			
			CStoreSCU objCStoreSCU = new CStoreSCU(objSession);

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


				//Genarating Dataset for Implant Template
				
				IDataSet objHangingProtocolDataSet = populateDataset();

				CStoreRQ objCStoreRQ = CStoreRQ.getDefaultRQ(objHangingProtocolDataSet);
				System.out.println("C-Store Request for Implant Template is created");

				//sending RQ to SCP
				if(objCStoreSCU.sendMessage(objCStoreRQ)) //sending request
					System.out.println("Implant Template Storage Operation performed");
				else
				{
					System.out.println("Implant Template Storage Operation Operation failed");

					//In case an ABORT is received from SCP during the Implant Template Storage Operation.
					if(objSession.getDIMSEAssociation() instanceof AAbort)
					{
						System.out.println("Abort arrives. Closing session.");
						objSession.close();
					}
				}

				//==============display status
				CStoreRSP objCStoreRSP = new CStoreRSP(objCStoreSCU.getDIMSEResponse().elementAt(0)); 
				System.out.println("Implant Template Storage Operation Status : " + objCStoreRSP.getStatus());

				/*
				 * *************************************************************************
				 * This block of code releases the association and 
				 * removes the connection with SCP.  
				 * *************************************************************************
				 */
				//Create A-Release-RQ to release the association
				AReleaseRQorRP objAReleaseRQorRP = new AReleaseRQorRP(EnumPDUType.RELEASE_RQ);

				//Send the A-Release-RQ
				if(objSession.sendAssociationMessage(objAReleaseRQorRP))
				{
					//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-Services-RQs and send them one by one.
					objSession.close();
				}
				else
				{
					System.out.println("Association cannot be released");
				}
			}
			else
			{
				System.out.println("Association cannot be established");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
}
}
