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

import java.io.IOException;
import java.net.InetSocketAddress;


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.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.cfind.commons.CFindRSP;
import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.DicomMessage;
import cdac.medinfo.sdk.dcm30_04.services.mwl.scu.MWLSCU;
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 tests a Stand Alone MWL SCU.
 * "Stand Alone" means that the User is required to write a minimal set of code to actually send a 
 * CStore Request. Once the required parameters are given to the CStoreSCU object it is 
 * capable of making a connection to the SCP, establishing association, sending the CStore Request and receiveing the 
 * DIMSE Response for the same. If User wants to handle the request sending scenarios by his/her code 
 * then please refer to sample code "MWL_SCU.java". 
 */
public class MWL_SCU_Stanalone 
{
	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");

			
			
			

			
			

			/*
			 * Creates TestStandaloneCStoreSCU.
			 */
			MWL_SCU_Stanalone objTestStanaloneMWL_SCU = new MWL_SCU_Stanalone();
			objTestStanaloneMWL_SCU.doMWL();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	/*
	 * This function starts thre MWL operation,
	 */
	public void doMWL()throws IOException
	{
		/* 
		 * Creates SCU with specified destination .
		 */
		InetSocketAddress addr = new InetSocketAddress("192.168.8.94",9000);
		MWLSCU objMWLSCU = new MWLSCU(addr);

		/*
		 * Send the C-Find DataSet with Affected SOP class UID of MWL
		 */
		ISingleCollection<IDataSet> objCFindDatasetList = new SingleCollection<IDataSet>();
		objCFindDatasetList.add(getDataSet());
		objMWLSCU.send("SDK","SDK",objCFindDatasetList);

		/*
		 * After the request is send user can get the response collection.
		 */

		ISingleCollection<DicomMessage> objSingleCollection = objMWLSCU.getDIMSEResponse();
		System.out.println("MWL operation Response Collection Size :: " + objSingleCollection.size());

		/*
		 * This will get the pending response from the Dicom Message and displays it.
		 */
		for(DicomMessage objDicomMessage : objSingleCollection)
		{
			CFindRSP objCFindRSP = new CFindRSP(objDicomMessage);
			System.out.println("MWL Response Status :" + objCFindRSP.getStatus());
			IDataSet objIDataSet2 = objDicomMessage.getDataSet();
			if(objIDataSet2 != null)
			{
				System.out.println("*********************************************");
				display(objIDataSet2);
				System.out.println("*********************************************");
			}
		}
	}

	/*
	 * 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(),"> ");					
			}
		}

	}

	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 method generates the query dataset for CFind operation.
	 * By manipulation in this code user can generate different patterns for a query dataset.
	 */
	private IDataSet getDataSet()
	{
		IDataSet objIDataSet = new DataSet();
		IDictionaryReader objDictionaryReader = objIDataSet.getDictionaryReader();
		ITransferSyntax objTS = objIDataSet.getTransferSyntax();
		objIDataSet.addDataElement(getDataElement(0x0008,0x0005, null, objDictionaryReader));

		//Scheduled Procedure Step
		{
			IDataTypeSQ objScheduledProcedureStepSQ = getSQ(0x0040,0x0100,objTS);
			IItem objScheduledProcedureStepItem = objScheduledProcedureStepSQ.getNewItem();
			objScheduledProcedureStepItem.addDataElement(getDataElement(0x0040,0x0001,null, objDictionaryReader));
			objScheduledProcedureStepItem.addDataElement(getDataElement(0x0040,0x0002,null, objDictionaryReader));
			objScheduledProcedureStepItem.addDataElement(getDataElement(0x0040,0x0003,null, objDictionaryReader));
			objScheduledProcedureStepItem.addDataElement(getDataElement(0x0008,0x0060,EnumModality.COMPUTED_RADIOGRAPHY.getValue(), objDictionaryReader));
			objScheduledProcedureStepSQ.addItem(objScheduledProcedureStepItem);
			objIDataSet.addDataElement(getDataElement(0x0040,0x0100,objScheduledProcedureStepSQ.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);
	}
}
