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

import java.io.IOException;


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.dicomnetcommons.EnumDataSink;
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.IDataSink;
import cdac.medinfo.sdk.dcm30_04.services.ian.iansinkimpl.IANDataSinkImpl;
import cdac.medinfo.sdk.dcm30_04.services.ncreate.scp.NCreateSCP;
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;
import cdac.medinfo.sdk.dcm30_04.utils.PairedCollection;

/**
 * This sample code defines the customized implementation of SCP for Instance Availability Notification Service Class.
 * This code process the request for service belonging to IAN service group.
 * Supported service for IAN is N-Create.
 * This implements all required methods of IProcessHandler for in order to process the request.
 * Connection establishment process : onConnect()
 * Association establishment process : onAssociateReceive()
 * Service Request process : onServiceRequest()
 * To create DB for IAN refer SQL Script NServiceDB.sql provided in install.
 */
public class IAN_Service_SCP_Cust_ProcHandler 
{
	public static void main(String[] args) throws IOException
	{
		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 IANService_SCP.
			IANService_SCP objIAN_SCP = new IANService_SCP();

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

			/*
			 * Create Sink with ConnectionString and driver String.
			 * IANDataSinkImpl is default implementation of library which uses JavaDB. 
			 * Sink Impl process the storage process for all IAN supported services. 
			 * The user has to start javaDB server before connection creation if Client Server model in java DB is used.
			 * The SQL Script needed to create database is provided at %InstallDir%/SQLScripts/NServiceDB.sql
			 * User has to first create the Database then it should be set in the IAN SCP.
			 * This DataSink should be set on process handler class working as IAN SCP.
			 * User can also provide its own implementation of IDataSink interface for IAN.
			 */
			String dataBasePath = "D:/Database/NServiceSDKdb";
			String ConnectionString = "jdbc:derby://localhost:5050/" + dataBasePath;
			String driverString = "org.apache.derby.jdbc.ClientDriver";

			IDataSink objIANDataSink = new IANDataSinkImpl(ConnectionString,driverString);

			/*
			 * Add Datasink on Process Handler.
			 * Here IANServices_SCP is acting as the Process handler,hence adding Data Sink to Process Handler.
			 */
			objIAN_SCP.addDataSink(EnumDataSink.IAN,objIANDataSink);

			/*
			 * Initializes the supporting 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.NCREATE_IAN;
			session.selectServices(arrenumServiceType);

			//Set IANServices_SCP as ProcessHandler.
			session.setIProcessHandler(objIAN_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();
		}
	}
}

/**
 * Note ProcessHandler is the class which implements interface IProcessHandler or extends ProcessHandler.
 * This class is implemented to process the IAN service requests.
 * 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 services for which SCP is started and Process handler(reference of test code) in SCPSession.
 * Its "start" method starts the SCP server.
 * When an SCU send connection request to SCP,SCP creates a client session for that SCU.
 * On SCP side a call back will be generated to 'onConnect' method of ProcessHandler whenever a connection request arrives.
 * Now user can retrieve 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 IProcessHandler.
 * User now can negotiate Association request with the default association and create AssociateAC or AssociationRJ
 * according to the acceptance or rejection.
 * The library provides AssociationNegotiator Class to negotiate and create appropriate response.
 * When a service request arrives the call back is made to 'onServiceRequest' method of ProcessHandler.
 * The user can retrieve the arrived Request from current ClientSession object passed in onServiceRequest method, processes it
 * and create respective Response.
 * SDK provides processRequest method in respective SCP to process the request and to generate response.
 * The SCP can handle multiple request simultaneously.
 * After this, when Association 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 IANService_SCP 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 instance 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 :
		{
			System.out.println("Association Request Received");
			AssociateRQ objAssociateRQ = (AssociateRQ)objIDIMSEAssociation;

			//get the default association from Client Session.
			DefaultAssociation objDefaultAssociation = objClientSession.getDefaultAssociation();

			//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);
			break;
		}
		case RELEASE_RQ :
		{
			System.out.println("Release Request Received");

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

			//Send Release 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");
			break;
		}
		}
	}

	/**
	 * This method notifies when a service related request is received.
	 * For Example,
	 * If N-Create-RQ is received,
	 * 		Create NCreateSCP using the ClientSession.
	 * 		Process the request using the NCreateSCP which process the request and returns a NCreateRSP.
	 * 		Send this response using the ClientSession.
	 * @see objClientSession Object of Client Session.
	 */
	public void onServiceRequest(ClientSession objClientSession)
	{
		DIMSEResponse objDResponse = null;

		//Retrieving DicomMessage from ClientSession which contains service request.
		DicomMessage objDicomMessage = objClientSession.getDicomMessage();

		//Populating DataSink Collection for processing of supported request for IAN service class.
		IPairedCollection<EnumDataSink,IDataSink> objDataSinkCollection = new PairedCollection< EnumDataSink,IDataSink >();
		objDataSinkCollection.put(EnumDataSink.IAN, getDataSink(EnumDataSink.IAN));

		try
		{
			/*
			 * If N-Create request for IAN is arrived, create NCreate SCP, setDataSink, process request
			 * and send message.
			 */
			System.out.println("N-Create Request Received");
			NCreateSCP objNCreateSCP = NCreateSCP.createInstance(objClientSession);

			objNCreateSCP.setDataSinkList(objDataSinkCollection);

			objDResponse = objNCreateSCP.processRequest(objDicomMessage);

			if(objDResponse != null)
				objClientSession.sendServiceMessage(objDResponse);
			System.out.println("N-Create Response Sent");
		}
		catch(Exception ioe)
		{
			ioe.printStackTrace();
			objClientSession.close();
		}
	}
}