/*******************************************************************************
 *  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.colorpalette.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.colorpalette.dbhelper.ColorPalette_StoreAgent;
import cdac.medinfo.sdk.dcm30_04.services.colorpalette.sourceimpl.ColorPaletteDataSourceImpl;
import cdac.medinfo.sdk.dcm30_04.services.colorpalette.sourceimpl.ColorPalette_Attributes;
import cdac.medinfo.sdk.dcm30_04.services.colorpalette.sourceimpl.ColorPalette_QueryModel;
import cdac.medinfo.sdk.dcm30_04.services.dicomnetcommons.EnumImplOpsStatus;
import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.IQueryModel;
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 Color Palette Service Class. This class contains methods to encode and decode Query Model.
 */
public class ColorPaletteQueryModel 
{
	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.
			 */
			ColorPaletteQueryModel objTest = new ColorPaletteQueryModel();
			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/Color_PaletteDB";
			String ConnectionString = "jdbc:derby://localhost:5050/" + dataBasePath;
			String driverString = "org.apache.derby.jdbc.ClientDriver";
			
			ColorPaletteDataSourceImpl objDataSourceImpl = new ColorPaletteDataSourceImpl(ConnectionString, driverString);
			
			IQueryModel objQueryModel = objTest.getQueryModel();
			
			IQueryModel objRstQueryModel = new ColorPalette_QueryModel();
			
			short shResult = objDataSourceImpl.find(objQueryModel, objRstQueryModel);
			
			if(shResult == EnumImplOpsStatus.SUCCESS.getValue())
			{
				ColorPalette_QueryModel objColorPaletteQRYMdl = (ColorPalette_QueryModel)objRstQueryModel;
				
				ISingleCollection<IDataSet> rstdatasetlist = new SingleCollection<IDataSet>();
				ITransferSyntax objITransferSyntax = new TransferSyntax();
				objColorPaletteQRYMdl.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 ColorPalette_QueryModel getQueryModel()
	{
		ColorPalette_QueryModel objColorPaletteQueryModel = new ColorPalette_QueryModel();
		
		ISingleCollection<ColorPalette_Attributes> objColorPaletteAttributes = objColorPaletteQueryModel.getColorPalette_AttributesList();
		
		ColorPalette_Attributes objColorPalette_Attributes = new ColorPalette_Attributes();

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

		objIDataSet.addDataElement(getDataElement(0x0008,0x0016, null, objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0008,0x0018, "1.2.840.10008.5.1.4.39.1", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0070,0x0080,null, objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0070,0x0081,null, objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0070,0x0084,null, objDictionaryReader));
		
		objColorPalette_Attributes.populate(objIDataSet);
		objColorPaletteAttributes.add(objColorPalette_Attributes);
		
		objColorPaletteQueryModel.setColorPalette_AttributesList(objColorPaletteAttributes);
		
		return objColorPaletteQueryModel;
	}
	
	/*
	 * This function populates the data set. Color Palette 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.1.5.1", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0008,0x0018, "1.2.840.10008.5.1.4.39.1", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0070,0x0080,"HOT_IRON", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0070,0x0081, "Hot Iron", objDictionaryReader));
		objIDataSet.addDataElement(getDataElement(0x0070,0x0084, "PixelMed^Publishing ", objDictionaryReader));
		
		IDataTypeSQ objAlternateConetentDescriptionSequence = getSQ(0x0070,0x0087,objTS);
		IItem objAlternateContentDescriptionSequenceItem = objAlternateConetentDescriptionSequence.getNewItem();
		objAlternateContentDescriptionSequenceItem.addDataElement(getDataElement(0x0070,0x0081, "Hot Iron", objDictionaryReader));
		objAlternateConetentDescriptionSequence.addItem(objAlternateContentDescriptionSequenceItem);
		objIDataSet.addDataElement(getDataElement(0x0070,0x0087,objAlternateConetentDescriptionSequence.getValue(), objDictionaryReader));
			
		IDataTypeSQ objLanguageCodeSequence = getSQ(0x0008,0x0006,objTS);
		IItem objCodeSqueneceMacroDependentItem = objLanguageCodeSequence.getNewItem();
		objCodeSqueneceMacroDependentItem.addDataElement(getDataElement(0x0008,0x0100,"fr", objDictionaryReader));		
		objCodeSqueneceMacroDependentItem.addDataElement(getDataElement(0x0008,0x0102,"RFC3066", objDictionaryReader));
		objCodeSqueneceMacroDependentItem.addDataElement(getDataElement(0x0008,0x0103,null, objDictionaryReader));
		objCodeSqueneceMacroDependentItem.addDataElement(getDataElement(0x0008,0x0104,"German", objDictionaryReader));
		objLanguageCodeSequence.addItem(objCodeSqueneceMacroDependentItem);
		objIDataSet.addDataElement(getDataElement(0x0008,0x0006,objLanguageCodeSequence.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/Color_PaletteDB";
			String ConnectionString = "jdbc:derby://localhost:5050/" + dataBasePath;
			String driverString = "org.apache.derby.jdbc.ClientDriver";
			ColorPalette_StoreAgent objColorPalette_StoreAgent = new ColorPalette_StoreAgent(ConnectionString, driverString);
			objColorPalette_StoreAgent.storeInstanceInfo(objIDataSet);
		}
		catch(Exception e)
		{
			System.out.println("Exception occured while insertion");
			e.printStackTrace();
		}
	}
}
