/*******************************************************************************
 *  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.testscu.securityprofiles.onlineelectronicstoragesecureuse;
import cdac.medinfo.sdk.dcm30_04.utils.DicomConstants;



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


import cdac.medinfo.sdk.dcm30_04.baselibs.ReferencedSOPSequence;
import cdac.medinfo.sdk.dcm30_04.baselibs.ReferencedSOPSequenceItem;
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.dicommodel.modules.StorageCommitmentModule;
import cdac.medinfo.sdk.dcm30_04.dicommodel.storagecommitment.StorageCommitmentIOD;
import cdac.medinfo.sdk.dcm30_04.dicommodel.xray.XRayAngiographicIOD;
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.association.RQPresContext;
import cdac.medinfo.sdk.dcm30_04.services.cstore.commons.CStoreRQ;
import cdac.medinfo.sdk.dcm30_04.services.cstore.scu.CStoreSCU;
import cdac.medinfo.sdk.dcm30_04.services.dicomnetcommons.EnumActionTypeID;
import cdac.medinfo.sdk.dcm30_04.services.naction.commons.NActionRQ;
import cdac.medinfo.sdk.dcm30_04.services.naction.commons.NActionRSP;
import cdac.medinfo.sdk.dcm30_04.services.naction.scu.NActionSCU;
import cdac.medinfo.sdk.dcm30_04.services.onlineelectronicstoragesecureuse.EnumSecureStorageStatus;
import cdac.medinfo.sdk.dcm30_04.services.onlineelectronicstoragesecureuse.OnlineElectronicStorageSecureUseProfile;
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;
import cdac.medinfo.sdk.dcm30_04.utils.IPairedCollection;
import cdac.medinfo.sdk.dcm30_04.utils.ISingleCollection;
import cdac.medinfo.sdk.dcm30_04.utils.PairedCollection;
import cdac.medinfo.sdk.dcm30_04.utils.SingleCollection;

/**
 * This class is to test Online Electronic Storage Secure Use Profile.
 * This sample test code sends C-Store Request and then Storage Commitment Request depending on the status of data set.
 * User of Test Secure Use Profile SCU  should start N-Event Report SCP after sending Storage Commitment Request to 
 * This class is to demonstrate use of Online Electronic Secure Storage Use profile in DICOM Communication Scenario on Service User.
 * This sample test code is basically a Storage Commitment SCU .It sends C-Store Request after Securing datset for Communication and then Storage Commitment Request.
 * User of Storage Commitment SCU should start N-Event Report SCP after sending Storage Commitment Request to 
 * SCP.
 */
public class SecureUseProfile_SCU
{

	private IPairedCollection<String , String> objSopInstanceFilePathCollection = new PairedCollection<String, String>();
	private IPairedCollection<String , String> objSopInstanceSopClassCollection = new PairedCollection<String, String>();
	private String strFilePath = null;
	private String strSopInstance = null;
	private String strSopClass = null;

	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 path is provided to create logs then it is created at USER %temp% DIR.
		objDicomConfig.enableLogging(EnumLoggingLevel.INFO, "C:\\DCM_Logs");

		
		
		

		

		/*
		 * creates object of TestCStoreSCU and Start CStore SCU.
		 */
		SecureUseProfile_SCU objTestCStoreSCU = new SecureUseProfile_SCU();
		objTestCStoreSCU.start();
	}

	/**
	 * This function performs the CStore and Storage Commitment operation.
	 */
	public void start()
	{
		try
		{
//			Enter the X-Ray Angiogram DICOM File with full path

			System.out.println("Enter the X-Ray Angiogram Dicom File with complete path");
			BufferedReader b_reader =new BufferedReader( new InputStreamReader( System.in ) );
			strFilePath = b_reader.readLine();

			// Creates the object of corresponding IOD by calling its constructor which takes File Name as a parameter and give its DataSet.
			XRayAngiographicIOD objXRayAngiographicIOD = new XRayAngiographicIOD(strFilePath);
			IDataSet objIDataSet = objXRayAngiographicIOD.getDataSet();
			strSopInstance = (String)objIDataSet.getValue(0x0008,0x0018);
			strSopClass = (String)objIDataSet.getValue(0x0008,0x0016);

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

			/*
			 * Initializes the service types and populates the default association
			 */
			ISingleCollection<RQPresContext> objRQPresContextCol = new SingleCollection<RQPresContext>();

			//RQ Pres Context for X-Ray
			RQPresContext objRQPresContextXRay = new RQPresContext();
			objRQPresContextXRay.setAbstractSyntaxName(EnumSOPClassUIDs.XRAYANGIOGRAPHICIOD.getValue());
			objRQPresContextXRay.addTransferSyntax(DicomConstants.TS_LOSSY_JPEG_8_BIT);
			objRQPresContextCol.add(objRQPresContextXRay);

			//RQ Pres Context for CT
			RQPresContext objRQPresContextCT = new RQPresContext();
			objRQPresContextCT.setAbstractSyntaxName(EnumSOPClassUIDs.CTIOD.getValue());
			objRQPresContextCT.addTransferSyntax(DicomConstants.TS_DEFAULT_IMPLICIT_VR_LITTLE_ENDIAN);
			objRQPresContextCol.add(objRQPresContextCT);

			//RQ Pres Context for NM
			RQPresContext objRQPresContextNM = new RQPresContext();
			objRQPresContextNM.setAbstractSyntaxName(EnumSOPClassUIDs.NMIOD.getValue());
			objRQPresContextNM.addTransferSyntax(DicomConstants.TS_EXPLICIT_VR_LITTLE_ENDIAN);
			objRQPresContextCol.add(objRQPresContextNM);

			//RQ Pres Context for SC
			RQPresContext objRQPresContextSC = new RQPresContext();
			objRQPresContextSC.setAbstractSyntaxName(EnumSOPClassUIDs.SCIOD.getValue());
			objRQPresContextSC.addTransferSyntax(DicomConstants.TS_DEFAULT_IMPLICIT_VR_LITTLE_ENDIAN);
			objRQPresContextCol.add(objRQPresContextSC);

			//RQ Pres Context for Storage Commitment
			RQPresContext objRQPresContextStorageCommitment = new RQPresContext();
			objRQPresContextStorageCommitment.setAbstractSyntaxName(DicomConstants.DCM_STORAGE_COMMITMENT_PUSH_MODEL_SOP_CLASS);
			objRQPresContextStorageCommitment.addTransferSyntax(DicomConstants.TS_DEFAULT_IMPLICIT_VR_LITTLE_ENDIAN);
			objRQPresContextCol.add(objRQPresContextStorageCommitment);

			//Load Default Association.
			DefaultAssociation objDefaultAssociation = new DefaultAssociation("SDK");
			objDefaultAssociation.loadAssociation(objRQPresContextCol);

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

			//Start SCU Session by providing the IP address and Port of SCP.
			objSession.start("192.168.8.101", 9000);

			//Create CStore SCU object using the current SCU Session.
			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");

				//Nevent SCP 
				NEventReportSCPHandler objNEventReportSCP = new NEventReportSCPHandler("SDK",9999,objSopInstanceFilePathCollection,objSopInstanceSopClassCollection);
				objNEventReportSCP.start();


				//Create Default CStore RQ by giving the parsed DataSet. This method uses
				// default values for the attributes in the request. These attributes can be
				//modified once the request object is created, before sending.
				CStoreRQ objCStoreRQ = CStoreRQ.getDefaultRQ(objIDataSet);

				OnlineElectronicStorageSecureUseProfile objSecureUseProfile = OnlineElectronicStorageSecureUseProfile.getOnlineElectronicStorageSecureUseProfile();
				objSecureUseProfile.enable(true);
				// Setting Secure Connection true
				objSecureUseProfile.setSecureConnection(true);

				boolean bIsCommitmentExpected = false;
				
				/* Securing the Dataset for verifying and keep tacking of Original and Other Copies of the same Dataset.
				 * In case of sending dataset with SOPInstanceStatus Original, the method informs whether to send Succeeding  Storage Commitment Request or Not.
				 */
				if(EnumSecureStorageStatus.STORAGECOMMITMENTEXPECTED == objSecureUseProfile.secureDataSetForStorage(objCStoreRQ.getDataSet(), true))
				{
					bIsCommitmentExpected = true;
					System.out.println("StorageCommitment Confirmation expected..");
				}
				else
					System.out.println("StorageCommitment Confirmation Not expected..");


				System.out.println("CStore Request initialized");

				//Send the C-Store-RQ and wait for a C-Store-RSP.
				//This method exits once the response is received. This response is 
				//added in the response collection maintained by the CStoreSCU which
				//can be retrived. This method return true if request is successfully sent 
				//to the SCP and false if the message cannot be sent to the SCP( for e.g. if 
				//the assocaition status is false or if SOP class UID is not agreed in agreed association.
				if(objCStoreSCU.sendMessage(objCStoreRQ)) //sending request
				{
					System.out.println("CStore Operation performed");
					if(true == bIsCommitmentExpected)
					{
						sendStorageCommitment(objSession);
					}

				}
				else
					System.out.println("C-Store Operation fails");

				System.out.println("Response Collection Size ==== " + objCStoreSCU.getDIMSEResponse().size());

				//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("Release response received");

					//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-Store-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 can not be established");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}


	/*
	 * This function sends the Storage Commitment Request.
	 */
	private void sendStorageCommitment(SCUSession objSession) throws IOException
	{
		objSopInstanceFilePathCollection.put(strSopInstance, strFilePath);
		objSopInstanceSopClassCollection.put(strSopInstance, strSopClass);


		// Create N-Action SCU for Sending N-Action Request
		NActionSCU objNActionSCU = new NActionSCU(objSession);

		//Get the data Set.
		IDataSet objIDataSet = getStorageCommitmentDataSet();

		System.out.println("NAction request for Storage Commitment is initialized");

		//Create N-Action RQ.
		NActionRQ objNActionRQ = NActionRQ.getDefaultRQ(DicomConstants.DCM_STORAGE_COMMITMENT_PUSH_MODEL_SOP_CLASS, DicomConstants.DCM_STORAGE_COMMITMENT_PUSH_MODEL_SOP_INSTANCE,EnumActionTypeID.STORAGE_COMMITMENT , objIDataSet);

		if(objNActionSCU.sendMessage(objNActionRQ))
		{
			System.out.println("NAction Response is received");
		}
		else
		{
			System.out.println("N-Action operation cannot be performed");
		}

		System.out.println("Response Collection Size ==== " + objNActionSCU.getDIMSEResponse().size());

		NActionRSP objActionRSP = new NActionRSP(objNActionSCU.getDIMSEResponse().elementAt(0));

		System.out.println("\nStatus of NAction response is: " + objActionRSP.getStatus());
		display(objNActionSCU.getDIMSEResponse().elementAt(0).getDataSet());
	}

	/*
	 * This function gets the Storage Commitment Data Set.
	 */
	private IDataSet getStorageCommitmentDataSet()
	{
		/*
		 * Create StorageCommitment IOD.
		 */
		StorageCommitmentIOD  objStorageCommitmentIOD = new StorageCommitmentIOD();
		StorageCommitmentModule objStorageCommitmentModule = objStorageCommitmentIOD.getStorageCommitmentModule();

		/*
		 * Set the Transaction UID.
		 */
		objStorageCommitmentModule.setTransactionUID("1");

		/*
		 * Add SOP class and SOP Instance to Reference SOP Sequence for which Storage COmmitment has to be done.
		 */
		ReferencedSOPSequence objReferencedSOPSequence = objStorageCommitmentModule.getReferencedSOPSequence();
		ReferencedSOPSequenceItem objReferencedSOPSequenceItem = objReferencedSOPSequence.getNewItem();
		objReferencedSOPSequenceItem.getSOPInstanceReferenceMacro().setReferencedSOPClassUID("1.2.840.10008.5.1.4.1.1.12.1");
		objReferencedSOPSequenceItem.getSOPInstanceReferenceMacro().setReferencedSOPInstanceUID("1.3.12.2.1107.5.4.3.284980.19951129.170916.9");
		objReferencedSOPSequence.addItem(objReferencedSOPSequenceItem);

		/*
		 * Get the Data Set from the Storage Commitment IOD.
		 */
		return objStorageCommitmentIOD.getDataSet();
	}

	/*
	 * This function displays the DataSet.
	 */
	@SuppressWarnings("unchecked")
	public 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 the items of sequence.
	 */
	public  static 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());						 
			}
		}	
	}

}
