/*******************************************************************************
 *  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.mwl.testcases.defaultscp;
import cdac.medinfo.sdk.dcm30_04.utils.DicomConstants;

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.EnumModality;
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.mwl.mwlsourceimpl.MWLDataSourceImpl;
import cdac.medinfo.sdk.dcm30_04.services.mwl.mwlsourceimpl.MWL_StoreAgent;
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 MWL 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 deafult implementaion
 * of the SDK.
 * To create DB for MWL refer SQL Script MWLServerDB.sql provided in install.
 */
public class MWL_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, "/home/user/Documents/DCM_Logs");

			/*
			 * Populating Database with dataset on which find request will be processed.
			 */
			MWL_CFind_SCP_Def_ProcHandler objTest = new MWL_CFind_SCP_Def_ProcHandler();
			IDataSet objIDataSet = objTest.populateDataset();
			objTest.storeInstanceInfo(objIDataSet);

			MWL_CFind_SCPHandler objMWL_CFind_SCPHandler = new MWL_CFind_SCPHandler();
			objMWL_CFind_SCPHandler.start();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}


	/*
	 * This function populates the data set. MWL service query on instance populated .
	 */
	public IDataSet populateDataset()
	{
		IDataSet objIDataSet = new DataSet();
		IDictionaryReader objDictionaryReader = objIDataSet.getDictionaryReader();
		ITransferSyntax objTS = objIDataSet.getTransferSyntax();
		//SOP Common Module
		objIDataSet.addDataElement(getDataElement(0x0008,0x0005, "SpecificCharSet", objDictionaryReader));

		//Scheduled Procedure Step
		{
			IDataTypeSQ objScheduledProcedureStepSQ = getSQ(0x0040,0x0100,objTS);
			IItem objScheduledProcedureStepItem = objScheduledProcedureStepSQ.getNewItem();
			String []strAETitle = new String[1];
			strAETitle[0] = "Title";
			strAETitle[1] = "Title";
			objScheduledProcedureStepItem.addDataElement(getDataElement(0x0040,0x0001,strAETitle, objDictionaryReader));
			objScheduledProcedureStepItem.addDataElement(getDataElement(0x0040,0x0002,"20000910", objDictionaryReader));
			objScheduledProcedureStepItem.addDataElement(getDataElement(0x0040,0x0003,"112000.000000", objDictionaryReader));
			objScheduledProcedureStepItem.addDataElement(getDataElement(0x0008,0x0060,EnumModality.COMPUTED_RADIOGRAPHY.getValue(), objDictionaryReader));
			objScheduledProcedureStepItem.addDataElement(getDataElement(0x0040,0x0006,"Physician Name", objDictionaryReader));
			objScheduledProcedureStepItem.addDataElement(getDataElement(0x0040,0x0007,"Scheduled Procedure Step Description", objDictionaryReader));
			objScheduledProcedureStepItem.addDataElement(getDataElement(0x0040,0x0010,"Station Name", objDictionaryReader));
			objScheduledProcedureStepItem.addDataElement(getDataElement(0x0040,0x0011,"Scheduled Proced", objDictionaryReader));
			{
				IDataTypeSQ objScheduledProtocolCodeSQ = getSQ(0x0040,0x0008, objTS);
				IItem objScheduledProtocolCodeItem = objScheduledProtocolCodeSQ.getNewItem();
				objScheduledProtocolCodeItem.addDataElement(getDataElement(0x0008,0x0100,"T-04000", objDictionaryReader));
				objScheduledProtocolCodeItem.addDataElement(getDataElement(0x0008,0x0102,"C4", objDictionaryReader));
				objScheduledProtocolCodeItem.addDataElement(getDataElement(0x0008,0x0103,"CPT-4", objDictionaryReader));
				objScheduledProtocolCodeItem.addDataElement(getDataElement(0x0008,0x0104,"Code Meaning", objDictionaryReader));
				{
					IDataTypeSQ objProtocolContextSQ = getSQ(0x0040,0x0440, objTS);
					IItem objProtocolContextItem = objProtocolContextSQ.getNewItem();
					objProtocolContextItem.addDataElement(getDataElement(0x0040,0xA040,"Value Type", objDictionaryReader));
					{
						IDataTypeSQ objConceptNameCodeSQ = getSQ(0x0040,0xA043, objTS);
						IItem objConceptNameCodeItem = objConceptNameCodeSQ.getNewItem();
						objConceptNameCodeItem.addDataElement(getDataElement(0x0008,0x0100,"T-04000", objDictionaryReader));
						objConceptNameCodeItem.addDataElement(getDataElement(0x0008,0x0102,"C4", objDictionaryReader));
						objConceptNameCodeItem.addDataElement(getDataElement(0x0008,0x0103,"CPT-4", objDictionaryReader));
						objConceptNameCodeItem.addDataElement(getDataElement(0x0008,0x0104,"Code Meaning", objDictionaryReader));
						objConceptNameCodeSQ.addItem(objConceptNameCodeItem);

						objProtocolContextItem.addDataElement(getDataElement(0x0040,0xA043,objConceptNameCodeSQ.getValue(), objDictionaryReader));
					}
					objProtocolContextItem.addDataElement(getDataElement(0x0040,0xA120,"20000910101010", objDictionaryReader));
					objProtocolContextItem.addDataElement(getDataElement(0x0040,0xA123,"Person Name", objDictionaryReader));
					objProtocolContextItem.addDataElement(getDataElement(0x0040,0xA160,"Text Value", objDictionaryReader));
					{
						IDataTypeSQ objConceptCodeSQ = getSQ(0x0040,0xA168, objTS);
						IItem objConceptCodeItem = objConceptCodeSQ.getNewItem();
						objConceptCodeItem.addDataElement(getDataElement(0x0008,0x0100,"T-04000", objDictionaryReader));
						objConceptCodeItem.addDataElement(getDataElement(0x0008,0x0102,"C4", objDictionaryReader));
						objConceptCodeItem.addDataElement(getDataElement(0x0008,0x0103,"CPT-4", objDictionaryReader));
						objConceptCodeItem.addDataElement(getDataElement(0x0008,0x0104,"Code Meaning", objDictionaryReader));
						objConceptCodeSQ.addItem(objConceptCodeItem);

						objProtocolContextItem.addDataElement(getDataElement(0x0040,0xA168,objConceptCodeSQ.getValue(), objDictionaryReader));
					}
					String []strNumericValue = new String[2];
					strNumericValue[0] = "1";
					strNumericValue[0] = "1";
					objProtocolContextItem.addDataElement(getDataElement(0x0040,0xA30A,strNumericValue, objDictionaryReader));
					{
						IDataTypeSQ objMeasurementUnitsCodeSQ = getSQ(0x0040,0x08EA, objTS);
						IItem objMeasurementUnitsCodeItem = objMeasurementUnitsCodeSQ.getNewItem();
						objMeasurementUnitsCodeItem.addDataElement(getDataElement(0x0008,0x0100,"T-04000", objDictionaryReader));
						objMeasurementUnitsCodeItem.addDataElement(getDataElement(0x0008,0x0102,"C4", objDictionaryReader));
						objMeasurementUnitsCodeItem.addDataElement(getDataElement(0x0008,0x0103,"CPT-4", objDictionaryReader));
						objMeasurementUnitsCodeItem.addDataElement(getDataElement(0x0008,0x0104,"Code Meaning", objDictionaryReader));
						objMeasurementUnitsCodeSQ.addItem(objMeasurementUnitsCodeItem);

						objProtocolContextItem.addDataElement(getDataElement(0x0040,0x08EA,objMeasurementUnitsCodeSQ.getValue(), objDictionaryReader));
					}
					objProtocolContextSQ.addItem(objProtocolContextItem);

					objScheduledProtocolCodeItem.addDataElement(getDataElement(0x0040,0x0440, objProtocolContextSQ.getValue(), objDictionaryReader));
				}
				objScheduledProtocolCodeSQ.addItem(objScheduledProtocolCodeItem);

				objScheduledProcedureStepItem.addDataElement(getDataElement(0x0040,0x0008, objScheduledProtocolCodeSQ.getValue(), objDictionaryReader));
			}
			objScheduledProcedureStepItem.addDataElement(getDataElement(0x0040,0x0012,"Pre Medication", objDictionaryReader));
			objScheduledProcedureStepItem.addDataElement(getDataElement(0x0040,0x0009,"Scheduled Pr", objDictionaryReader));
			objScheduledProcedureStepItem.addDataElement(getDataElement(0x0032,0x1070,"Requested Contrast Agent", objDictionaryReader));
			objScheduledProcedureStepItem.addDataElement(getDataElement(0x0040,0x0020,"SCHEDULED", objDictionaryReader));

			objScheduledProcedureStepSQ.addItem(objScheduledProcedureStepItem);

			objIDataSet.addDataElement(getDataElement(0x0040,0x0100,objScheduledProcedureStepSQ.getValue(), objDictionaryReader));
		}

		//Requested Procedure
		objIDataSet.addDataElement(getDataElement(0x0040,0x1001, "0", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0032,0x1060, "Requested Proced", objDictionaryReader));
		{
			IDataTypeSQ objRequestedProcedureCodeSQ = getSQ(0x0032,0x1064, objTS);
			IItem objRequestedProcedureCodeItem = objRequestedProcedureCodeSQ.getNewItem();
			objRequestedProcedureCodeItem.addDataElement(getDataElement(0x0008,0x0100,"T-04000", objDictionaryReader));
			objRequestedProcedureCodeItem.addDataElement(getDataElement(0x0008,0x0102," C4", objDictionaryReader));
			objRequestedProcedureCodeItem.addDataElement(getDataElement(0x0008,0x0103,"CPT-4", objDictionaryReader));
			objRequestedProcedureCodeItem.addDataElement(getDataElement(0x0008,0x0104,"Code Meaning", objDictionaryReader));
			objRequestedProcedureCodeSQ.addItem(objRequestedProcedureCodeItem);

			objIDataSet.addDataElement(getDataElement(0x0032,0x1064,objRequestedProcedureCodeSQ.getValue(), objDictionaryReader));
		}
		objIDataSet.addDataElement(getDataElement(0x0020,0x000D, "1.2.840.10008.5.1.4.31", objDictionaryReader));
		{
			IDataTypeSQ objReferencedStudySQ = getSQ(0x0008,0x1110, objTS);
			IItem objReferencedStudyItem = objReferencedStudySQ.getNewItem();
			objReferencedStudyItem.addDataElement(getDataElement(0x0008,0x1150,"1.3.46.670589.17.1.7.1.1.11", objDictionaryReader));
			objReferencedStudyItem.addDataElement(getDataElement(0x0008,0x1155,"1.3.46.670589.17.1.7.1.1.11", objDictionaryReader));
			objReferencedStudySQ.addItem(objReferencedStudyItem);

			objIDataSet.addDataElement(getDataElement(0x0008,0x1110,objReferencedStudySQ.getValue(), objDictionaryReader));
		}
		objIDataSet.addDataElement(getDataElement(0x0040,0x1003,"STAT", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0040,0x1004,"Patient Transport Arrangements", objDictionaryReader));

		//Imaging Service Request
		objIDataSet.addDataElement(getDataElement(0x0008,0x0050,"Accession Number", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0032,0x1032,"Requesting Physician", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0008,0x0090,"Referring Physicians Name", objDictionaryReader));

		//Visit Identification
		objIDataSet.addDataElement(getDataElement(0x0038,0x0010,"Admission ID", objDictionaryReader));

		//Visit Status
		objIDataSet.addDataElement(getDataElement(0x0038,0x0300,"Current Patient Location", objDictionaryReader));

		//Visit Relationship
		{
			IDataTypeSQ objReferencedPatientSQ = getSQ(0x0008,0x1120, objTS);
			IItem objReferencedPatientItem = objReferencedPatientSQ.getNewItem();
			objReferencedPatientItem.addDataElement(getDataElement(0x0008,0x1150,"1.3.46.670589.17.1.7.1.1.11", objDictionaryReader));
			objReferencedPatientItem.addDataElement(getDataElement(0x0008,0x1155,"1.3.46.670589.17.1.7.1.1.11", objDictionaryReader));
			objReferencedPatientSQ.addItem(objReferencedPatientItem);

			objIDataSet.addDataElement(getDataElement(0x0008,0x1120,objReferencedPatientSQ.getValue(), objDictionaryReader));
		}

		//Patient Identification
		objIDataSet.addDataElement(getDataElement(0x0010,0x0010,"Patients Name", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0010,0x0020,"Patient ID", objDictionaryReader));

		//Patient Demographic
		objIDataSet.addDataElement(getDataElement(0x0010,0x0030,"19940910", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0010,0x0040,"Patients Sex", objDictionaryReader));
		{
			IDataTypeSQ objPatientPrimaryLanguageSQ = getSQ(0x0010,0x0101, objTS);
			IItem objPatientPrimaryLanguageItem = objPatientPrimaryLanguageSQ.getNewItem();
			objPatientPrimaryLanguageItem.addDataElement(getDataElement(0x0008,0x0100,"T-04000", objDictionaryReader));
			objPatientPrimaryLanguageItem.addDataElement(getDataElement(0x0008,0x0102,"C4", objDictionaryReader));
			objPatientPrimaryLanguageItem.addDataElement(getDataElement(0x0008,0x0104,"CPT-4", objDictionaryReader));
			{
				IDataTypeSQ objPatientPrimaryLanguageCodeModifierSQ = getSQ(0x0010,0x0102, objTS);
				IItem objPatientPrimaryLanguageCodeModifierItem = objPatientPrimaryLanguageCodeModifierSQ.getNewItem();
				objPatientPrimaryLanguageCodeModifierItem.addDataElement(getDataElement(0x0008,0x0100,"T-04000", objDictionaryReader));
				objPatientPrimaryLanguageCodeModifierItem.addDataElement(getDataElement(0x0008,0x0102,"C4", objDictionaryReader));
				objPatientPrimaryLanguageCodeModifierItem.addDataElement(getDataElement(0x0008,0x0104,"Code Meaning", objDictionaryReader));
				objPatientPrimaryLanguageCodeModifierSQ.addItem(objPatientPrimaryLanguageCodeModifierItem);

				objPatientPrimaryLanguageItem.addDataElement(getDataElement(0x0010,0x0102, objPatientPrimaryLanguageCodeModifierSQ.getValue(), objDictionaryReader));
			}
			objPatientPrimaryLanguageSQ.addItem(objPatientPrimaryLanguageItem);

			objIDataSet.addDataElement(getDataElement(0x0010,0x0101,objPatientPrimaryLanguageSQ.getValue(), objDictionaryReader));
		}
		objIDataSet.addDataElement(getDataElement(0x0010,0x1030,"22", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0040,0x3001,"Confidentiality constraint on patient data", objDictionaryReader));

		//Patient Medical
		objIDataSet.addDataElement(getDataElement(0x0038,0x0500,"Patient State", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0010,0x21C0,(short)26, objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0010,0x2000,"Medical Alerts", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0010,0x2110,"Contrast Allergies", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0038,0x0050,"Special Needs", 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 MWL_StoreAgent.
			 */
			String dataBasePath = "C://Documents/MWL_SDKdb";
			String ConnectionString = "jdbc:derby://localhost:5050/" + dataBasePath ;
			String driverString = "org.apache.derby.jdbc.ClientDriver";
			MWL_StoreAgent objMWL_StoreAgent = new MWL_StoreAgent(ConnectionString, driverString);
			objMWL_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 extened 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 serive requests. It process all the request , 
 * generates response and sents 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 MWL_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 = "C://Documents/MWL_SDKdb";
			String ConnectionString = "jdbc:derby://localhost:5050/" + dataBasePath ;
			String driverString = "org.apache.derby.jdbc.ClientDriver";

			IDataSource objMWLDataSource = new MWLDataSourceImpl(ConnectionString,driverString);
			addDataSource(EnumDataSource.MWL,objMWLDataSource);

			/*
			 * The session needs to be configured to load customized association according to service types selected. 
			 */
			EnumServiceType[] arrenumServiceType = new EnumServiceType[1];
			arrenumServiceType[0] = EnumServiceType.CFIND_MWL;
			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();
		}
	} 
}

