/*******************************************************************************
 *  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.cservices.withdb.testcases.customizedscp;

import cdac.medinfo.sdk.dcm30_04.enums.EnumCommandField;
import cdac.medinfo.sdk.dcm30_04.enums.EnumLoggingLevel;
import cdac.medinfo.sdk.dcm30_04.enums.EnumPDUType;

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.AssociationNegotiator;
import cdac.medinfo.sdk.dcm30_04.services.association.DefaultAssociation;
import cdac.medinfo.sdk.dcm30_04.services.association.IDIMSEAssociation;
import cdac.medinfo.sdk.dcm30_04.services.cfind.scp.CFindSCP;
import cdac.medinfo.sdk.dcm30_04.services.cmove.scp.CMoveSCP;
import cdac.medinfo.sdk.dcm30_04.services.dicomnetcommons.EnumDataSource;
import cdac.medinfo.sdk.dcm30_04.services.dicomnetcommons.EnumServiceType;
import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.DIMSEResponse;
import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.DicomMessage;
import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.IDataSource;
import cdac.medinfo.sdk.dcm30_04.services.javadbhelper.DataSourceImpl;
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.IPairedCollection;

/**
 * This class is to Test C-Move SCP in Asynchronous Mode. In Asynchronous Mode SCU sends multiple service request
 * to SCP without waiting for the Response. The SCP processes the request and sends the response.
 * This is the customized implementation of the test code for C-Move Services.
 * This sample codes is to show how user can define its own implementation for handling connection, association and service request in Asynchronous mode.
 * In this sample test code all the required methods of IProcessHandler are implemented (onConnect(), onAssociateReceive() and onServiceRequest()) 
 * and their definition is provided here. User can define these methods according to his need.
 * To create DB for C-Services refer SQL Script DICOMServerDB.sql provided in install. 
 */
public class CMove_SCP_Async_Cust_ProcHandler 
{
	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");

			/*
			 * Create DataSourceImpl with ConnectionString and driver String.
			 * DataSourceImpl is default implementation of library which uses JavaDB to 
			 * MOVE Data Elements.The user has to start javaDB server before connection
			 * if Client Server model in java DB is used.
			 * This DataSource should be set in CMove SCP.
			 * User can also provide its own implementation of IDataSource interface
			 * to move the attributes.
			 */
			String dataBasePath = "C:/Database/SDKdb";
			String ConnectionString = "jdbc:derby://localhost:5050/" + dataBasePath;
			String driverString = "org.apache.derby.jdbc.ClientDriver";

			IDataSource objIDataSource = new DataSourceImpl(ConnectionString,driverString);
			/*
			 * Creates CMove_SCP_Async.
			 */
			AsyncCMoveSCPHandler scp = new AsyncCMoveSCPHandler();

			/*
			 * Add Datasource on Process Handler. Here AsyncCMoveSCPHandler is acting as the Process handler 
			 * for the test code. Hence adding Data Source to Process Handler.
			 */
			scp.addDataSource(EnumDataSource.CSERVICES, objIDataSource);

			//Create SCP Session 
			SCPSession session = new SCPSession();

			/*
			 * Initializes the service types and sets it on SCP Session
			 */
			EnumServiceType[] arrenumServiceType = new EnumServiceType[2];
			arrenumServiceType[0] = EnumServiceType.CMOVE;
			arrenumServiceType[1] = EnumServiceType.CFIND_DEFAULT;
			session.selectServices(arrenumServiceType);

			/*
			 * Add Third party AE Title in C-Move SCP. these are the C-Store Servers 
			 * in C-Move.
			 */
			scp.addSupportedAETitles("DCMRCV", "192.168.8.94", 9002);

			//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 test code is to test  C-Move Service in Asynchronous mode. In Asynchronous Mode SCU sends multiple service request
 * to SCP without waiting for the Response. The SCP processes the request and sends the response.
 * Note ProcessHandler is the class which implements interface IProcessHandler or extends ProcessHandler.
 * This class is implemented to test the C-Move SCP.
 * In order to run the following class , please refer to this link($Link) to create the environment.
 * To implement an SCP of a particular we need to do the following things :
 * To create SCP user should either has to implement class IProcessHandler (which is an interface ) or extends Process handler.
 * If test code implements process handler then user has to provide implementation of the methods declared in the interface.
 * Otherwise he can extend the process handler which contains the default implementation for processing of association and service request.
 * Create the SCPSession object which maintains the session of the SCP. 
 * Set the default association and Process handler(reference of test code) in SCPSession.
 * Its "start" method starts the SCP server.
 * When an SCU connects to the C-Move SCP then when the connection is accepted client session is created for that SCU.
 * When SCU connects to the C-Move SCP the call back on onConnect of ProcessHandler is made. Now user can get the connection parameters
 * from client session and can decide whether to accept the connection or not. To accept the connection user has to
 * pass true to acceptConnection function in ClientSession class.
 * After the connection is established the next request expected to arrive at SCP is Association request.
 * When Association request arrives, callback is made to onAssociateReceive method of ProcessHandler.
 * User now can negotiate Association request with the default association and creates AssociateAC or Reject.
 * The library provides AssociationNegotiator Class to negotiate and create appropriate response.
 * SCP accepts the association request for Asynchronous mode by setting Number of operations invoked and performed to 0.
 * When C-Move request arrives the call back is made to onServiceRequest method of ProcessHandler.
 * The user can get the C-Move Request from current ClientSession object passed in onServiceRequest method, processes it
 * and creates C-Move-RSP. SDK provides processRequest method in CMoveSCP to process the request and generates response.
 * The C-Move SCP now act as C-Store SCu for third party and connects to it. Perform C-Store for the matches found and
 * then releases the Association. Then final C-move RSP is send to the user.
 * The C-Move SCP can handle multiple request simultaneously.
 * After this, when A-Release-RQ arrives , Create Release response and send it to the SCU.
 * Whenever the SCU goes down its client session is also closed or SCP can close the client session 
 * by calling close method of client session.
 */
class AsyncCMoveSCPHandler extends ProcessHandler
{
	/**
	 * This method notifies when a new client connection is requested. A decision is to be made whether to
	 * accept or reject the connection.  
	 * @param objClientSession object of Client Session.
	 */
	public void onConnect(ClientSession objClientSession)
	{
		objClientSession.acceptConnection(true);
	}

	/**
	 * This method notifies when Association Request, Associate Release Request or Abort is received from one of the 
	 * SCUs. 
	 * If Association Request is received,
	 * 		Create Association Negotiator which negotiates the request with the existing default association and
	 * 		creates an AgreedAssociation which contains the negotiated association values. AssociationNegotiator
	 * 		returns the Association Response as AssociateAC when request is accepted or returns AssociateRJ is 
	 * 		none of the values in Association Request are acceptable.
	 * 	If Associate Release Request is received,
	 * 		Create a Associate Release Response and send the response to the SCU using the respective ClientSession.
	 *  If Abort is received,
	 *  	An Abort response must be generated and sent using ClientSession
	 * @param objClientSession object of Client Session.
	 */
	public void onAssociateReceive(ClientSession objClientSession) 
	{
		//Get Association RQ
		IDIMSEAssociation objIDIMSEAssociation = objClientSession.getDIMSEAssociation();
		EnumPDUType enumPDUType = objIDIMSEAssociation.getPDUType();
		IDIMSEAssociation objAssociationRSP = null;

		//For Association Request negotiate with Default Association and generate Response
		switch(enumPDUType)
		{
		case ASSOCIATE_RQ :
		{
			AssociateRQ objAssociateRQ = (AssociateRQ)objIDIMSEAssociation;	

			System.out.println("Association Request Recieved");

			//get the default association from Client Session.
			DefaultAssociation objDefaultAssociation = objClientSession.getDefaultAssociation();
			objDefaultAssociation.getRQUserInfo().setMaxNumOpsInvoked((short)0);
			objDefaultAssociation.getRQUserInfo().setMaxNumOpsPerformed((short)0);

			//Negotiate and get Response
			AssociationNegotiator objAssNegotiator = new AssociationNegotiator();
			objAssociationRSP = objAssNegotiator.negotiate(objDefaultAssociation, objAssociateRQ);

			//set agreed association in client Session.
			objClientSession.setAgreedAssociation(objAssNegotiator.getAgreedAssociation());

			//Send Response
			objClientSession.sendAssociationMessage(objAssociationRSP);
			System.out.println("Response of Association Request is sent");
			break;
		}
		case RELEASE_RQ :
		{
			System.out.println("Release Request Received");

			//Create Release Response.
			objAssociationRSP = new AReleaseRQorRP(EnumPDUType.RELEASE_RP);

			//Send Response
			objClientSession.sendAssociationMessage(objAssociationRSP);
			System.out.println("Release Response sent");

			//Close Client Session
			objClientSession.close();
			break;
		}
		case ABORT :
		{
			System.out.println("Abort has arrived Stop Porcessing -- Association is no longer available");
		}
		}
	}

	/**
	 * This method notifies when a service related request is received.
	 * For Example,
	 * If C-Move-RQ is received,
	 * 		Create CMoveRSP using the ClientSession.
	 * 		Process the request using the CMoveSCP which searches for the key attribute
	 * 		then act as C-Store SCU , establishes Association with C-Store Server , performs 
	 * 		C-Store and then release the association. For each C-Store sends the pending response to C-move SCU
	 * 		After all C-Store request send final response to the C-move SCU.
	 * 		Send this response using the ClientSession.
	 *  
	 * @see objClientSession object of Client Session.
	 */
	public void onServiceRequest(ClientSession objClientSession)
	{

		/*
		 * Create CMove_SCP get RQ from ClientSession call processRequest and pass C_Move_RQ on CMove_SCP
		 * receive response from CMove_SCP sendResponse using ClientSession
		 */
		DicomMessage objDicomMessage = objClientSession.getDicomMessage();
		EnumCommandField enumCommandField = objDicomMessage.getCommandType();

		if(enumCommandField == EnumCommandField.C_MOVE_RQ)
		{
			System.out.println("C-Move Request Received");

			DIMSEResponse objDResponse = null;
			CMoveSCP objCMoveSCP = CMoveSCP.createInstance(objClientSession); 

			try
			{
				IPairedCollection<String, String> objPairedCollection = getSupportedAETitles();
				String strSupportedAETitle = objPairedCollection.get("DCMRCV");
				String[] strArray = strSupportedAETitle.split(":");
				String strIP = strArray[0];
				int iPort = Integer.parseInt(strArray[1]);

				/*
				 * Set third party C-Store information on C-Move SCP.
				 */
				objCMoveSCP.addAETitleInfo("DCMRCV", strIP, iPort);

				/*
				 * Process CMove Request using the CMoveSCP which searches for the key attribute
				 * then act as C-Store SCU , establishes Association with C-Store Server , performs 
				 * C-Store and then release the association.
				 * For each C-Store sends the pending response to C-move SCU
				 * After all C-Store request send final response to the C-move SCU.
				 */
				IDataSource objDataSource = getDataSource(EnumDataSource.CSERVICES);

				/*
				 * Set Data SOurce on C-Move SCP
				 */
				objCMoveSCP.setDataSource(objDataSource);

				//Provide the request to C-Move SCP for processing.  processRequest function will process the
				//request and returns the response
				objDResponse = objCMoveSCP.processRequest(objClientSession.getDicomMessage());
				System.out.println("C-Move RSP sent");

				/*
				 * Send the service message through Client Session.
				 */
				if(objDResponse != null)
					objClientSession.sendServiceMessage(objDResponse);

			}catch(Exception ioe)
			{
				ioe.printStackTrace();
				objClientSession.close();
			}
		}
		else if(enumCommandField == EnumCommandField.C_FIND_RQ)
		{
			/*
			 * Create CFIND_SCP get RQ from ClientSession call processRequest and pass C_FIND_RQ on CFIND_SCP
			 * receive response from CFIND_SCP sendResponse using ClientSession
			 */
			System.out.println("C-Find Request Received");

			DIMSEResponse objDResponse = null;
			CFindSCP objCFindSCP = CFindSCP.createInstance(objClientSession); 
			try
			{
				/*
				 * Process CFind Request using the CFindSCP which actually searches the key attribute 
				 * in the data set and returns a CFindRSP pending response containing the dataset and final success response.
				 */
				/*
				 * Set Data SOurce on C-Find SCP
				 */
				objCFindSCP.setDataSourceList(getDataSourceList());

//				Provide the request to C-Find SCP for processing.  processRequest function will process the
				//request and returns the response
				objDResponse = objCFindSCP.processRequest(objClientSession.getDicomMessage());

				/*
				 * Send the service message through Client Session.
				 */
				if(objDResponse != null)
					objClientSession.sendServiceMessage(objDResponse);

				System.out.println("C-Find response sent");
			}catch(Exception ioe)
			{
				ioe.printStackTrace();
				objClientSession.close();
			}
		}
	}
}

