package cdac.medinfo.sdk.dcm30_04.services.implanttemplate.testcases.customizedscp;

import java.io.IOException;

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.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.cget.scp.CGetSCP;
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.IDataSource;
import cdac.medinfo.sdk.dcm30_04.services.implanttemplate.dbhelper.ImplantTemplate_StoreAgent;
import cdac.medinfo.sdk.dcm30_04.services.implanttemplate.sourceimpl.ImplantTemplateDataSourceImpl;
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;

/**
 * This is the customized implementation of the test code for Implant Template's C-Get Service.
 * This sample codes is to show how user can define its own implementation for handling connection, association and service request.
 * 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 Implant Template Services refer SQL Script ImplantTemplateDB.sql  provided in install. 
 */
public class ImplantTemplate_CGet_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");
			
			
			/*
			 * Populating Database with data set on which find request will be processed.
			 */
			ImplantTemplate_CGet_SCP_Cust_ProcHandler objTest = new ImplantTemplate_CGet_SCP_Cust_ProcHandler();
			IDataSet objIDataSet = objTest.populateDataset();
			objTest.storeInstanceInfo(objIDataSet);
			
			
			/*
			 * Create DataSourceImpl with ConnectionString and driver String.
			 * DataSourceImpl is default implementation of library which uses JavaDB to 
			 * GET 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 CGET SCP.
			 * User can also provide its own implementation of IDataSource interface
			 * to GET the attributes.
			 */
			String dataBasePath = "D:/SDKDatabase/ImplantTemplateDB";
			String ConnectionString = "jdbc:derby://localhost:5050/" + dataBasePath;
			String driverString = "org.apache.derby.jdbc.ClientDriver";

			IDataSource objIDataSource = new ImplantTemplateDataSourceImpl(ConnectionString,driverString);

			/*
			 * Creates CGetSCP.
			 */
			CGetSCPHandler scp = new CGetSCPHandler();

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

			//Create SCP Session 
			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[2];
			arrenumServiceType[0] = EnumServiceType.CSTORE_IMPLANTTEMPLATE;
			arrenumServiceType[1] = EnumServiceType.CGET_IMPLANTTEMPLATE;
			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 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.IMPLANTASSEMBLYTEMPLATEIOD.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.44.4", objDictionaryReader));
	objIDataSet.addDataElement(getDataElement(0x0008,0x0018, "1.2.3.4.5.6.7.0.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 stores the dataset instance to database.
 */
public void storeInstanceInfo(IDataSet objIDataSet)
{
	try
	{
		/*
		 * Create DataBase and store dataset to database using ImplantTemplate_StoreAgent.
		 */
		String dataBasePath = "D:/SDKDatabase/ImplantTemplateDB";
		String ConnectionString = "jdbc:derby://localhost:5050/" + dataBasePath;
		String driverString = "org.apache.derby.jdbc.ClientDriver";
		ImplantTemplate_StoreAgent  objImplantTemplate_StoreAgent = new ImplantTemplate_StoreAgent(ConnectionString, driverString);
		objImplantTemplate_StoreAgent.storeInstanceInfo(objIDataSet);
	}
	catch(Exception e)
	{
		System.out.println("Exception occured while insertion");
		e.printStackTrace();
	}
}
}

/**
 * Note ProcessHandler is the class which implements interface IProcessHandler or extends ProcessHandler.
 * This class is implemented to test the C-Get SCP of Implant Template Service Class.
 * 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-get SCP then when the connection is accepted client session is created for that SCU.
 * When SCU connects to the C-Get 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.
 * When C-Get request arrives the call back is made to onServiceRequest method of ProcessHandler.
 * The user can get the C-Get Request from current ClientSession object passed in onServiceRequest method, processes it
 * and creates C-Get-RSP. SDK provides processRequest method in Cget to process the request and generates response.
 * The C-Get SCP now act as C-Store SCU and sends C-Store to the C-get SCU(which in turn act as C-Store SCP). 
 * Perform C-Store for the matches found and Then final C-Get RSP is send to the user.
 * The C-Get 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 CGetSCPHandler 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 :
		{
			System.out.println("Association Request is 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);
			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);

			//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-Get-RQ is received,
	 * 		Create CGet RSP using the ClientSession.
	 * 		Process the request using the CGetSCP which will act as a C-Store SCU. Found the matches for the 
	 * 		key attribute, sends c-store request to the C-get SCU (Which should act as C-Store SCP ) and then sends the
	 * 		C-get Final response to the C-Get SCU. 
	 * 		Send this response using the ClientSession.
	 * @param objClientSession object of Client Session.
	 */
	public void onServiceRequest(ClientSession objClientSession)
	{
		System.out.println("C-Get request received");

		/*
		 * Create CGET_SCP and get RQ from ClientSession 
		 * Call processRequest and pass CGET_SCP on CGET_SCP
		 * Receive response from CGET_SCP sendResponse using ClientSession
		 */
		DIMSEResponse objDResponse = null;
		CGetSCP objCGetSCP = CGetSCP.createInstance(objClientSession); 

		try
		{
			/*
			 * Process C-Get Request using the CGetSCP which will act as a C-Store SCU. Found the matches for the 
			 * key attribute, sends c-store request to the C-get SCU (Which should act as C-Store SCP ) and then sends the
			 * C-get Final response to the C-Get SCU. 
			 */
			IDataSource objDataSource = getDataSource(EnumDataSource.IMPLANTTEMPLATE);

			/*
			 * Set Data Source in C-Get SCP.
			 */
			objCGetSCP.setDataSource(objDataSource);

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

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

			System.out.println("C-Get response sent");

		}catch(Exception ioe)
		{
			ioe.printStackTrace();
			objClientSession.close();
		}
	}
}
