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

import cdac.medinfo.sdk.dcm30_04.baselibs.DataSet;
import cdac.medinfo.sdk.dcm30_04.baselibs.DisplaySubsystemSequence;
import cdac.medinfo.sdk.dcm30_04.baselibs.DisplaySubsystemSequenceItem;
import cdac.medinfo.sdk.dcm30_04.baselibs.EquipmentAdministratorSequence;
import cdac.medinfo.sdk.dcm30_04.baselibs.EquipmentAdministratorSequenceItem;
import cdac.medinfo.sdk.dcm30_04.baselibs.QAResultsSequence;
import cdac.medinfo.sdk.dcm30_04.baselibs.QAResultsSequenceItem;
import cdac.medinfo.sdk.dcm30_04.baselibs.TargetLuminanceCharacteristicsSequence;
import cdac.medinfo.sdk.dcm30_04.baselibs.TargetLuminanceCharacteristicsSequenceItem;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IDataSet;
import cdac.medinfo.sdk.dcm30_04.dicommodel.displaysystem.DisplaySystemIOD;
import cdac.medinfo.sdk.dcm30_04.dicommodel.modules.DisplaySystemModule;
import cdac.medinfo.sdk.dcm30_04.dicommodel.modules.QAResultsModule;
import cdac.medinfo.sdk.dcm30_04.dicommodel.modules.SOPCommonModule;
import cdac.medinfo.sdk.dcm30_04.dicommodel.modules.TargetLuminanceCharacteristicsModule;
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.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.displaysystemmanagement.dbhelper.DisplaySystem_DBAgent;
import cdac.medinfo.sdk.dcm30_04.services.displaysystemmanagement.sourceimpl.DisplaySystem_SourceImpl;
import cdac.medinfo.sdk.dcm30_04.services.nget.scp.NGetSCP;
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.DicomConstants;


/**
 * This is the customized implementation of the test code for Display System Services.
 * 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.
 * This test code uses N-Get SCP to process the Display System request. Once the Data Source Implementation for 
 * Display System is set on N-Get SCP it is capable of handling N-Get request.
 * To create DB for Display System  refer SQL Script DisplaySystemManagementDB.sql provided in install.
 */

public class Display_System_NGet_SCP_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");
			/*
			 * Populating Database with data set on which find request will be processed.
			 */
			Display_System_NGet_SCP_Cust_ProcHandler objTest = new Display_System_NGet_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 
			 * find 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 NGet SCP.
			 * User can also provide its own implementation of IDataSource interface
			 * to find the attributes.
			 */
			String dataBasePath = "D:/SDKDatabase/DisplaySystemManagementDB";
			String ConnectionString = "jdbc:derby://localhost:5050/" + dataBasePath;
			String driverString = "org.apache.derby.jdbc.ClientDriver";

			IDataSource objDisplaySystemDataSource = new DisplaySystem_SourceImpl(ConnectionString,driverString);

			/*
			 * Creates DisplaySystem_NGet_SCPHandler SCP.
			 */
			DisplaySystem_NGet_SCPHandler scp = new DisplaySystem_NGet_SCPHandler();
			scp.addDataSource(EnumDataSource.DISPLAY_SYSTEM_MANAGEMENT,objDisplaySystemDataSource);

			/*
			 * 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.NGET_DISPLAY_SYSTEM_MANAGEMENT;
			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. Display System service query on instance populated.
	 */
	public IDataSet populateDataset()
	{
		IDataSet objIDataSet = new DataSet();
		objIDataSet.getDictionaryReader();
		objIDataSet.getTransferSyntax();
		DisplaySystemIOD objDisplaySystemIOD=new DisplaySystemIOD();			

		
		SOPCommonModule objSOPCommonModule=objDisplaySystemIOD.getSOPCommonModule();
		String []arrStrSpecificCharacterSet = new String[1];
		arrStrSpecificCharacterSet[0] = "ISO 2022 IR 87";
		objSOPCommonModule.setSpecificCharacterSet(arrStrSpecificCharacterSet);
		objSOPCommonModule.setSOPClassUID(EnumSOPClassUIDs.DISPLAYSYSTEMIOD.getValue().toString());
		objSOPCommonModule.setSOPInstanceUID("1.2.840.10008.5.1.1.40.1");
		
		DisplaySystemModule objDisplaySystemModule= objDisplaySystemIOD.getDisplaySystemModule();
		objDisplaySystemModule.setManufacturer("Tablet Corp");
		objDisplaySystemModule.setInstitutionName("JIRA Hospital");
		objDisplaySystemModule.setInstitutionAddress("Bunkyo-ku, Tokyo, Japan");
		objDisplaySystemModule.setDeviceSerialNumber("AA1B22CCCC3D");
		objDisplaySystemModule.setStationName("TABLET1");
		objDisplaySystemModule.setInstitutionalDepartmentName("Radiology Dept.");
		
		EquipmentAdministratorSequence objEquipmentAdministratorSequence=objDisplaySystemModule.getEquipmentAdministratorSequence();
		EquipmentAdministratorSequenceItem objEquipmentAdministratorSequenceItem=objEquipmentAdministratorSequence.getNewItem();
		objEquipmentAdministratorSequenceItem.setPersonName("Yamada^Tarou");
		
		objDisplaySystemModule.setNumberOfDisplaySubsystems((short)2);		

		DisplaySubsystemSequence objDisplaySubsystemSequence=objDisplaySystemModule.getDisplaySubsystemSequence();
		
		DisplaySubsystemSequenceItem objDisplaySubsystemSequenceItem1=objDisplaySubsystemSequence.getNewItem();
		objDisplaySubsystemSequenceItem1.setDisplaySubsystemID((short)2);
		objDisplaySubsystemSequenceItem1.setDisplaySubsystemDescription("Embedded LCD");
		objDisplaySubsystemSequenceItem1.setDisplaySubsystemName("DS1");
		objDisplaySubsystemSequence.addItem(objDisplaySubsystemSequenceItem1);		
		
		DisplaySubsystemSequenceItem objDisplaySubsystemSequenceItem2=objDisplaySubsystemSequence.getNewItem();
		objDisplaySubsystemSequenceItem2.setDisplaySubsystemID((short)1);
		objDisplaySubsystemSequenceItem2.setDisplaySubsystemDescription("DSS2ofWSX");
		objDisplaySubsystemSequenceItem2.setDisplaySubsystemName("Diagnostic");
		objDisplaySubsystemSequence.addItem(objDisplaySubsystemSequenceItem2);

		TargetLuminanceCharacteristicsModule objTargetLuminanceCharacteristicsModule=objDisplaySystemIOD.getTargetLuminanceCharacteristicsModule();		
		TargetLuminanceCharacteristicsSequence objTargetLuminanceCharacteristicsSequence=objTargetLuminanceCharacteristicsModule.getTargetLuminanceCharacteristicsSequence();
		
		TargetLuminanceCharacteristicsSequenceItem objTargetLuminanceCharacteristicsSequenceItem1=objTargetLuminanceCharacteristicsSequence.getNewItem();		
		objTargetLuminanceCharacteristicsSequenceItem1.setLuminanceCharacteristicsID((short)1);
		objTargetLuminanceCharacteristicsSequenceItem1.setDisplayFunctionType("GAMMA");
		objTargetLuminanceCharacteristicsSequenceItem1.setTargetMinimumLuminance((float)0.75);
		objTargetLuminanceCharacteristicsSequenceItem1.setTargetMaximumLuminance((float)300);
		objTargetLuminanceCharacteristicsSequenceItem1.setGammaValue((float)2.2);		
		objTargetLuminanceCharacteristicsSequence.addItem(objTargetLuminanceCharacteristicsSequenceItem1);

		TargetLuminanceCharacteristicsSequenceItem objTargetLuminanceCharacteristicsSequenceItem2=objTargetLuminanceCharacteristicsSequence.getNewItem();		
		objTargetLuminanceCharacteristicsSequenceItem2.setLuminanceCharacteristicsID((short)2);
		objTargetLuminanceCharacteristicsSequenceItem2.setDisplayFunctionType("GSDF");
		objTargetLuminanceCharacteristicsSequenceItem2.setTargetMinimumLuminance((float)0.75);
		objTargetLuminanceCharacteristicsSequenceItem2.setTargetMaximumLuminance((float)521);
		objTargetLuminanceCharacteristicsSequenceItem2.setGammaValue((float).210);		
		objTargetLuminanceCharacteristicsSequence.addItem(objTargetLuminanceCharacteristicsSequenceItem2);

		QAResultsModule objQAResultsModule=objDisplaySystemIOD.getQAResultsModule();
		QAResultsSequence objQAResultsSequence=objQAResultsModule.getQAResultsSequence();
		QAResultsSequenceItem objQAResultsSequenceItem=objQAResultsSequence.getNewItem();
		objQAResultsSequenceItem.setDisplaySubsystemID((short)1);
		objQAResultsSequence.addItem(objQAResultsSequenceItem);		
		
		return  objDisplaySystemIOD.getDataSet();
	}



	/*
	 * This function stores the dataset instance to database.
	 */
	public void storeInstanceInfo(IDataSet objIDataSet)
	{
		try
		{
			/*
			 * Create DataBase and store dataset to database using DisplaySystem_DBAgent.
			 */
			String dataBasePath = "D:/SDKDatabase/DisplaySystemManagementDB";
			String ConnectionString = "jdbc:derby://localhost:5050/" + dataBasePath;
			String driverString = "org.apache.derby.jdbc.ClientDriver";
			DisplaySystem_DBAgent  objDisplaySystemDBAgent = new DisplaySystem_DBAgent(ConnectionString, driverString);
			objDisplaySystemDBAgent.createDisplaySystemInstance(objIDataSet, DicomConstants.DCM_DISPLAY_SYSTEM_SOP_INSTANCE.toString());
		
		}
		catch(Exception e)
		{
			System.out.println("Exception occured while insertion");
			e.printStackTrace();
		}
	}
}

/**
 * This class is implemented to test the Display System 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 Display System SCP then when the connection is accepted client session is created for that SCU.
 * When SCU connects to the Display System 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 N-Get request for Display System arrives the call back is made to onServiceRequest method of ProcessHandler.
 * The user can get the N-Get Request from current ClientSession object passed in onServiceRequest method, processes it
 * and creates N-Get-RSP. SDK provides processRequest method in N-Get SCP to process the request and generates response.
 * The SCP search for the matches in javaDB and sends pending response for each match found.
 * Then success response is send to the SCU.
 * The N-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 DisplaySystem_NGet_SCPHandler 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 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 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.
	 * @param objClientSession  object of client session.
	 */
	public void onServiceRequest(ClientSession objClientSession)
	{
		/*
		 * Create NGetSCP get RQ from ClientSession call processRequest and pass N-GetRequest on NGetSCP
		 * receive response from NGetSCP sendResponse using ClientSession
		 */
		DIMSEResponse objDResponse = null;
		NGetSCP objNGetSCP = NGetSCP.createInstance(objClientSession); 
		try
		{
			System.out.println("Display System  :: N-Get Request Received");
			/*
			 * Process NGet Request.
			 * Set DatasourceImpl for Display System in N-Get SCP.
			 */
			objNGetSCP.setDataSourceList(getDataSourceList());
			objDResponse = objNGetSCP.processRequest(objClientSession.getDicomMessage());

			/*
			 * Send the service message through Client Session.
			 */
			if(objDResponse != null)
				objClientSession.sendServiceMessage(objDResponse);
			System.out.println("Display System  :: N-Get  Response Sent");
		}catch(Exception ioe)
		{
			ioe.printStackTrace();
		}
	}

	/**
	 * Closes the Client Session,
	 */
	public void onClose(ClientSession objClientSession)
	{
		objClientSession.close();
	}
}

