/*******************************************************************************
 *  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.HangingProtocol.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.HangingProtocolDefinitionSequence;
import cdac.medinfo.sdk.dcm30_04.baselibs.ImplicitDE;
import cdac.medinfo.sdk.dcm30_04.baselibs.NominalScreenDefinitionSequence;
import cdac.medinfo.sdk.dcm30_04.baselibs.SQ;
import cdac.medinfo.sdk.dcm30_04.baselibs.ScheduledProcedureStepSequence;
import cdac.medinfo.sdk.dcm30_04.baselibs.ScreenSpecificationsMacro;
import cdac.medinfo.sdk.dcm30_04.baselibs.ScreenSpecificationsMacroDependentItem;
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.dictionaryreaderwriters.DictionaryReader;
import cdac.medinfo.sdk.dcm30_04.enums.EnumLoggingLevel;
import cdac.medinfo.sdk.dcm30_04.enums.EnumSOPClassUIDs;
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.hangingprotocol.sourceimpl.HangingProtocolDataSourceImpl;
import cdac.medinfo.sdk.dcm30_04.services.hangingprotocol.sourceimpl.HangingProtocol_Attributes;
import cdac.medinfo.sdk.dcm30_04.services.hangingprotocol.sourceimpl.HangingProtocol_QueryModel;
import cdac.medinfo.sdk.dcm30_04.services.hangingprotocol.sourceimpl.HangingProtocol_StoreAgent;
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 is the Query model implementation of the test code for Hanging Protocol Services.
 */
public class HangingProtocolQueryModel 
{
	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.
			 */
			HangingProtocolQueryModel objTest = new HangingProtocolQueryModel();
			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 = "c:/DataBase/HangingProtocolServerDB";
			String ConnectionString = "jdbc:derby://localhost:5050/" + dataBasePath;
			String driverString = "org.apache.derby.jdbc.ClientDriver";

			HangingProtocolDataSourceImpl objDataSourceImpl = new HangingProtocolDataSourceImpl(ConnectionString, driverString);
			
			IQueryModel objQueryModel = objTest.getQueryModel();
			
			IQueryModel objRstQueryModel = new HangingProtocol_QueryModel();
			
			short shResult = objDataSourceImpl.find(objQueryModel, objRstQueryModel);
			
			if(shResult == EnumImplOpsStatus.SUCCESS.getValue())
			{
				HangingProtocol_QueryModel objRsltMWLQRYMdl = (HangingProtocol_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 : -");
				IDataSet objRSLTDataSet = rstdatasetlist.elementAt(0);
				
				objTest.display(objRSLTDataSet);
			}

			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 displays 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);
				}	 
			}
		}
	}
	/**
	 * This function gets the data set. Hanging protocol service query on instance populated.
	 */
	public HangingProtocol_QueryModel getQueryModel()
	{
		HangingProtocol_QueryModel HangingProtocolQueryModel = new HangingProtocol_QueryModel();
		
		ISingleCollection<HangingProtocol_Attributes> objHangingProtocolAttributes = HangingProtocolQueryModel.getHangingProtocol_AttributesList();
		
		HangingProtocol_Attributes objHangingProtocol_Attributes = new HangingProtocol_Attributes();

		IDataSet objIDataSet = new DataSet();
		IDictionaryReader objIDictionaryReader = objIDataSet.getDictionaryReader();
		objIDataSet.addDataElement(getDataElement(0x0000,0x0002,null, objIDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0000,0x0120, null, objIDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0000,0x0800, null, objIDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0008,0x0016, null, objIDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0008,0x0018, "1.2.840.10008.5.1.4.1.1.4", objIDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0008,0x0060, "MR", objIDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0072,0x0102,null, objIDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0072,0x0104,null, objIDictionaryReader));
		objHangingProtocol_Attributes.populate(objIDataSet);
		objHangingProtocolAttributes.add(objHangingProtocol_Attributes);
		
		HangingProtocolQueryModel.setHangingProtocol_AttributesList(objHangingProtocolAttributes);
		
		return HangingProtocolQueryModel;
	}
	
	/**
	 * This function populates the data set. Hanging protocol 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.HANGINGPROTOCOLIOD.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.38.1", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0008,0x0018, "1.2.840.10008.5.1.4.1.1.2", objDictionaryReader));
		
		
		IDataTypeSQ objHangingProtocolDefinitionSequenceSQ = getSQ(0x0072,0x000C,objTS);
		IItem objHangingProtocolDefinitionSequenceItem = objHangingProtocolDefinitionSequenceSQ.getNewItem();		
		objHangingProtocolDefinitionSequenceItem.addDataElement(getDataElement(0x0008,0x0060, "CT", objDictionaryReader));
		objHangingProtocolDefinitionSequenceSQ.addItem(objHangingProtocolDefinitionSequenceItem);
		objIDataSet.addDataElement(getDataElement(0x0072,0x000C,objHangingProtocolDefinitionSequenceSQ.getValue(), objDictionaryReader));
		
			
		objIDataSet.addDataElement(getDataElement(0x0072,0x0100, (short)1, objDictionaryReader));		
		IDataTypeSQ objNominalScreenDefinitionSequenceSQ = getSQ(0x0072,0x0102,objTS);
		IItem objScreenSpecificationsMacroDependentItem = objNominalScreenDefinitionSequenceSQ.getNewItem();
		objScreenSpecificationsMacroDependentItem.addDataElement(getDataElement(0x0072,0x0104,(short) 10, objDictionaryReader));		
		objScreenSpecificationsMacroDependentItem.addDataElement(getDataElement(0x0072,0x0106,(short) 10, objDictionaryReader));

		objNominalScreenDefinitionSequenceSQ.addItem(objScreenSpecificationsMacroDependentItem);
		objIDataSet.addDataElement(getDataElement(0x0072,0x0102,objNominalScreenDefinitionSequenceSQ.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 = "c:/DataBase/HangingProtocolServerDB";
			String ConnectionString = "jdbc:derby://localhost:5050/" + dataBasePath;
			String driverString = "org.apache.derby.jdbc.ClientDriver";
			HangingProtocol_StoreAgent objHangingProtocol_StoreAgent = new HangingProtocol_StoreAgent(ConnectionString, driverString);
			objHangingProtocol_StoreAgent.storeInstanceInfo(objIDataSet);
		}
		catch(Exception e)
		{
			System.out.println("Exception occured while insertion");
			e.printStackTrace();
		}
	}
}
