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

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.services.dicomnetcommons.EnumDataSource;
import cdac.medinfo.sdk.dcm30_04.services.dicomnetcommons.EnumServiceType;
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.ProcessHandler;
import cdac.medinfo.sdk.dcm30_04.services.scp.commons.SCPSession;
import cdac.medinfo.sdk.dcm30_04.utils.DicomConfig;

/**
 * This is the default implementation of the sample test code for Implant Template 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.
 * To create DB for Implant Template refer SQL Script ImplantTemplateDB.sql provided in install.
 */
public class ImplantTemplate_CFind_SCP_Def_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 dataset on which find request will be processed.
			 */
			ImplantTemplate_CFind_SCP_Def_ProcHandler objTest = new ImplantTemplate_CFind_SCP_Def_ProcHandler();
			IDataSet objIDataSet = objTest.populateDataset();
			objTest.storeInstanceInfo(objIDataSet);

			ImplantTemplate_CFind_SCPHandler objImplantTemplate_CFind_SCPHandler = new ImplantTemplate_CFind_SCPHandler();
			objImplantTemplate_CFind_SCPHandler.start();
		}
		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(0x0008,0x0016, "1.2.840.10008.5.1.4.45.1", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0008,0x0018, "1.2.3.4.5.6.7.1.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");
		}
	}
}

/**
 * This class inherits all the lifecycle methods involved in a communication with client.
 * This class is extended 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 service requests. It process all the request , 
 * generates response and sends 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 ImplantTemplate_CFind_SCPHandler extends ProcessHandler
{
	/**
	 * Starts SCP server at iPort and local host.
	 * @throws IOException Signals IOException if IO operation fails.
	 */
	public void start()
	{
		try
		{
			/*
			 * Create SCP session.
			 */
			SCPSession objSCPSession = new SCPSession();

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

			IDataSource objImplantTemplateDataSourceImpl = new ImplantTemplateDataSourceImpl(ConnectionString,driverString);
			addDataSource(EnumDataSource.IMPLANTTEMPLATE,objImplantTemplateDataSourceImpl);

			/*
			 * The session needs to be configured to load customized association according to service types selected. 
			 */
			EnumServiceType[] arrenumServiceType = new EnumServiceType[1];
			arrenumServiceType[0] = EnumServiceType.CFIND_IMPLANTTEMPLATE;
			objSCPSession.selectServices(arrenumServiceType);

			/*
			 * Set Process handler.
			 */
			objSCPSession.setIProcessHandler(this);
			
			/*
			 * 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.
			 */ 
			//objSCPSession.setTimeOut(5000);

			/*
			 * Start the server.
			 */
			objSCPSession.start("SDK",9000);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	} 
}
