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

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.baselibs.SQ;
import cdac.medinfo.sdk.dcm30_04.baselibs.TransferSyntax;
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.EnumImplOpsStatus;
import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.IQueryModel;
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.implanttemplate.sourceimpl.ImplantTemplate_Attributes;
import cdac.medinfo.sdk.dcm30_04.services.implanttemplate.sourceimpl.ImplantTemplate_QueryModel;
import cdac.medinfo.sdk.dcm30_04.utils.DicomConfig;
import cdac.medinfo.sdk.dcm30_04.utils.ICollectionIterator;
import cdac.medinfo.sdk.dcm30_04.utils.ISingleCollection;
import cdac.medinfo.sdk.dcm30_04.utils.SingleCollection;

/**
 *  This class represents Query Model for Implant Template Service Class. This class contains methods to encode and decode Query Model.
 */
public class ImplantTemplateQueryModel 
{
	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.
			 */
			ImplantTemplateQueryModel objTest = new ImplantTemplateQueryModel();
			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 CFind SCP.
			 * User can also provide its own implementation of IDataSource interface
			 * to find the attributes.
			 */
			String dataBasePath = "D:/SDKDatabase/ImplantTemplateDB";
			String ConnectionString = "jdbc:derby://localhost:5050/" + dataBasePath;
			String driverString = "org.apache.derby.jdbc.ClientDriver";

			ImplantTemplateDataSourceImpl objDataSourceImpl = new ImplantTemplateDataSourceImpl(ConnectionString, driverString);
			
			IQueryModel objQueryModel = objTest.getQueryModel();
			
			IQueryModel objRstQueryModel = new ImplantTemplate_QueryModel();
			
			short shResult = objDataSourceImpl.find(objQueryModel, objRstQueryModel);
			
			if(shResult == EnumImplOpsStatus.SUCCESS.getValue())
			{
				ImplantTemplate_QueryModel objRsltMWLQRYMdl = (ImplantTemplate_QueryModel)objRstQueryModel;
				
				ISingleCollection<IDataSet> rstdatasetlist = new SingleCollection<IDataSet>();
				ITransferSyntax objITransferSyntax = new TransferSyntax();
				objRsltMWLQRYMdl.encode(objITransferSyntax, rstdatasetlist);
				System.out.println("\n \nData Set for C Get : -");
				if(rstdatasetlist.size()>0)
				{
				IDataSet objRSLTDataSet = rstdatasetlist.elementAt(0);				
				objTest.display(objRSLTDataSet);
				}
				else
					System.out.println("\n\n No Match Found!!!");
			}

			System.out.println("\n\n shResult = " + shResult);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

	}
	
	/*
	 * Displays the DataElements of Dataset
	 */
	private void display(IDataSet objIDataSet)
	{
		ICollectionIterator<IDataElement> objIDataSetIterator = objIDataSet.iterator();

		System.out.println("Tag     Value");
		while(objIDataSetIterator.hasNext())
		{
			IDataElement objDataElement = objIDataSetIterator.next();				

			if(!(objDataElement.getDicomValue() instanceof SQ))
			{

				System.out.println(objDataElement.getTag().getGroupNumber()+"    "+
						objDataElement.getTag().getElementNumber()+"    "+
						objDataElement.getDicomValue().toString());
			}
			else  
			{
				displaySequence((SQ)objDataElement.getDicomValue(),"> ");					
			}
		}

	}

	/*
	 * This method diaplays the SQ data type.
	 */
	private void displaySequence(SQ objSQDataElement,String ss)
	{
		ICollectionIterator<IItem> objSQItemIterator = objSQDataElement.iterator();
		int i = 1;
		while(objSQItemIterator.hasNext())
		{
			System.out.println("ITEM :"+ i++ );
			IItem objItem = objSQItemIterator.next();
			ICollectionIterator<IDataElement> objDataElementIterator = objItem.iterator();
			while(objDataElementIterator.hasNext())
			{
				IDataElement objDataElement = objDataElementIterator.next();

				if(!(objDataElement.getDicomValue() instanceof SQ))
				{
					System.out.println(ss +objDataElement.getTag().getGroupNumber()+"    "+
							objDataElement.getTag().getElementNumber()+"    "+
							objDataElement.getDicomValue().toString());						 

				}
				else
				{
					displaySequence((SQ)objDataElement.getDicomValue(),ss+ss);
				}	 
			}
		}
	}
	
	public ImplantTemplate_QueryModel getQueryModel()
	{
		ImplantTemplate_QueryModel objImplantTemplateQueryModel = new ImplantTemplate_QueryModel();
		
		ISingleCollection<ImplantTemplate_Attributes> objImplantTemplateAttributes = objImplantTemplateQueryModel.getImplantTemplate_AttributesList();
		
		ImplantTemplate_Attributes objImplantTemplate_Attributes = new ImplantTemplate_Attributes();

		IDataSet objIDataSet = new DataSet();
		IDictionaryReader objDictionaryReader = objIDataSet.getDictionaryReader();

		objIDataSet.addDataElement(getDataElement(0x0008,0x0016, null, objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0008,0x0018, "1.2.3.4.5.6.7.1.2", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0000,0x0120,null, objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0000,0x0800,null, objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0008,0x0070,null, objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0022,0x1095,null, objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0068,0x6210,null, objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0022,0x1097,null, objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0068,0x6226,null, objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0068,0x6221,null, objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0068,0x6223,null, objDictionaryReader));
		objImplantTemplate_Attributes.populate(objIDataSet);
		objImplantTemplateAttributes.add(objImplantTemplate_Attributes);
		
		objImplantTemplateQueryModel.setImplantTemplate_AttributesList(objImplantTemplateAttributes);
		
		return objImplantTemplateQueryModel;
	}
	
	/*
	 * This function populates the data set. Implant Template 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.DCM_IMPLANT_ASSEMBLY_TEMPLATE_INFORMATION_MODEL_FIND.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.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 MWL_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();
		}
	}
}
