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

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;


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.EnumLoggingLevel;
import cdac.medinfo.sdk.dcm30_04.services.basicapplicationlevelconfidentialityprofile.BasicAppLevelConfidentialityProfile;
import cdac.medinfo.sdk.dcm30_04.services.basicapplicationlevelconfidentialityprofile.EnumProfileAlgorithm;
import cdac.medinfo.sdk.dcm30_04.services.dicomnetcommons.EnumServiceType;
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;

/**
 * This is the default implementation of the sample test code for C-Store 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 default implementation
 * of the SDK.
 * Here onServiceRequest() method after processing the request decrypts the data set using Basic Application Level Confidentiality Profile
 * and stores it at the location specified.
 * To create DB for C-Services refer SQL Script DICOMServerDB.sql provided in install.
 */
public class CStore_SCP 
{
	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 CStore_SCP.
			 */
			CStoreSCPHandler scp = new CStoreSCPHandler();
			scp.addSinkImpl();

			/*
			 * Created SCP session and set Default association and Process Handler on it.
			 */
			SCPSession session = new SCPSession();

			/*
			 * Initializes the service types and sets it on SCP Session
			 * EnumService Type configures SCP Session to load corresponding association context and start
			 * corresponding DIMSE Services.
			 */
			EnumServiceType []arrenumServiceType = new EnumServiceType[1];
			arrenumServiceType[0] = EnumServiceType.CSTORE_DEFAULT;
			session.selectServices(arrenumServiceType);

			//Set Process Handler as the SCP TestCode
			session.setIProcessHandler(scp);
			
			/*
			 * 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",9000);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
}

/**
 * This class inherits all the lifecycle methods involved in a communication with client.
 * This class is extened from the ProcessHandler class of the SDK for DICOM.
 * ProcessHandler class is the default processor of SDK for DICOM which is capable
 * of handling connection , association and serive requests. It process all the request , 
 * generates response and sents it to SCU.
 * Once the required parameters are set on ProcessHandler class of SDK for DICOM
 * then it will handle all the Association and Service requests.
 */
class CStoreSCPHandler extends ProcessHandler
{
	public void addSinkImpl()
	{
		try
		{
			/*
			 * The DataSet is serialized at the Storage Path provided on C-Store SCP.
			 * If No Storage Path is provide on C-Store SCP then File is serialized at "%temp%/CDAC-SDK/DCM-J/DicomDump"
			 * in User Temp Folder.
			 */
			setStoragePath("C:\\StoragePath");

		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * Here onServiceRequest() method after processing the request decrypts the data set using 
	 * Basic Application Level Confidentiality Profile and stores it at the location specified.
	 */
	public void onServiceRequest(ClientSession objClientSession) 
	{
		try
		{
			/*
			 * Get the clone of the recieved Data Set.
			 */
			IDataSet objIDataSet = (IDataSet)objClientSession.getDicomMessage().getDataSet();



			/*
			 * Displaying the Data Set which is received in C-Store Request.
			 */
			System.out.println("***************************************************************************************");
			System.out.println("**************** Displaying Data Set which is received in C-Store Request *****************************************");
			System.out.println("***************************************************************************************");
			display(objIDataSet);


			/*
			 * Get the Secret Key and decrypt the Data Set.
			 */
			String strFilePath = null;
			System.out.println("Enter the secret key required for decryption");
			BufferedReader b_reader =new BufferedReader( new InputStreamReader( System.in ) );
			strFilePath = b_reader.readLine();
			FileInputStream objFileInputStream = new FileInputStream(strFilePath);
			byte[] objKey = new byte[objFileInputStream.available()];
			objFileInputStream.read(objKey);

			/*
			 * Decrypt the data set using the key provided to re-identify the attributes.
			 */
			BasicAppLevelConfidentialityProfile objBasicAppLevelConfidentialityProfile = new BasicAppLevelConfidentialityProfile();

			IDataSet objDecryptedDataSet = objBasicAppLevelConfidentialityProfile.decryptDataSet(objIDataSet, EnumProfileAlgorithm.AES, objKey, null);

			System.out.println("***************************************************************************************");
			System.out.println("**************** Displaying Decrypted Data Set *****************************************");
			System.out.println("***************************************************************************************");
			display(objDecryptedDataSet);

			objDecryptedDataSet.iterator();

			objClientSession.getDicomMessage().setDataSet(objDecryptedDataSet);
			/*
			 * call onServiceRequest of process handler to process C-Store Request.
			 */
			super.onServiceRequest(objClientSession);

		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}


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

	/*
	 * This method Display the SQ data type.
	 */
	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());						 

				}
				else
				{
					displaySequence((SQ)objDataElement.getDicomValue(),ss+ss);
				}	 
			}
		}
	}
}
