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

import java.io.IOException;
import java.sql.SQLException;
import java.util.Locale;

import cdac.medinfo.sdk.dcm30_04.baselibs.DataSet;
import cdac.medinfo.sdk.dcm30_04.baselibs.ExplicitDE;
import cdac.medinfo.sdk.dcm30_04.baselibs.ImplicitDE;
import cdac.medinfo.sdk.dcm30_04.baselibs.PrintJobDescriptionSequence;
import cdac.medinfo.sdk.dcm30_04.baselibs.PrintJobDescriptionSequenceItem;
import cdac.medinfo.sdk.dcm30_04.baselibs.ReferencedPrintJobSequence;
import cdac.medinfo.sdk.dcm30_04.baselibs.ReferencedPrintJobSequenceItem;
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.IDictionaryReader;
import cdac.medinfo.sdk.dcm30_04.commoninterface.ITag;
import cdac.medinfo.sdk.dcm30_04.dicommodel.modules.PrintQueueModule;
import cdac.medinfo.sdk.dcm30_04.dicommodel.print.PrintQueueIOD;
import cdac.medinfo.sdk.dcm30_04.enums.EnumCommandField;
import cdac.medinfo.sdk.dcm30_04.enums.EnumSOPClassUIDs;
import cdac.medinfo.sdk.dcm30_04.services.dicomnetcommons.EnumImplOpsStatus;
import cdac.medinfo.sdk.dcm30_04.services.dicomnetcommons.ICommandSet;
import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.DicomMessage;
import cdac.medinfo.sdk.dcm30_04.services.print.dbhelper.Print_DBAgent;
import cdac.medinfo.sdk.dcm30_04.utils.DicomConfig;
import cdac.medinfo.sdk.dcm30_04.utils.DicomConstants;
import cdac.medinfo.sdk.dcm30_04.utils.DicomLogger;
import cdac.medinfo.sdk.dcm30_04.utils.ISingleCollection;
import cdac.medinfo.sdk.dcm30_04.utils.ResourceBundleWrapper;
import cdac.medinfo.sdk.dcm30_04.utils.StandardMethods;

/**
 * This class process N-Get Request for Print Job IOD.
 */
class PrintJobImpl
{
	/**
	 * This is default Constructor for PrintJobImpl.
	 */
	public PrintJobImpl() {
		super();
	}
	
	/**
	 * This fucntion processes retrieve function for Print Job SOP Instance.
	 */
	@SuppressWarnings("unchecked")
	short retrievePrintJobSOPInstance(Print_DBAgent objPrintDBAgent, DicomMessage objDicomMessage, ISingleCollection<IDataSet> objDataSetColl, String strValue) throws IOException, SQLException
	{
		EnumCommandField enumRequestType = objDicomMessage.getCommandType();
		switch(enumRequestType)
		{
		case N_GET_RQ :
		{
			ICommandSet objICommandSet = objDicomMessage.getCommandSet();
			IDataSet objPrintQueue = objPrintDBAgent.retrieveSOPInstance(EnumSOPClassUIDs.PRINTQUEUEMANAGEMENTIOD, null, DicomConstants.DCM_PRINT_QUEUE_MANAGEMENT_SOP_INSTANCE);

			//This data set should be made according to the Agreed associaiton TS.
			IDataSet objRstDataSet = new DataSet();
			if(objPrintQueue != null)
			{
				ISingleCollection<ITag> objTagCollection = null;
				Object objValue =  objICommandSet.getValue(0x0000,0x1005);
				if(objValue != null)
				{
					objTagCollection = (ISingleCollection<ITag>)objValue;
				}

				PrintQueueIOD objPrintQueueIOD = new PrintQueueIOD(objPrintQueue);
				PrintQueueModule objPrintQueueModule = objPrintQueueIOD.getPrintQueueModule();
				PrintJobDescriptionSequence objPrintJobDescriptionSequence = objPrintQueueModule.getPrintJobDescriptionSequence();
				ISingleCollection<PrintJobDescriptionSequenceItem> objPrintJobDescriptionSequenceItemColl = (ISingleCollection<PrintJobDescriptionSequenceItem>)objPrintJobDescriptionSequence.getValue();

				ReferencedPrintJobSequenceItem objReferencedPrintJobSequenceItem = null;
				for(PrintJobDescriptionSequenceItem objPrintJobDescriptionSequenceItem : objPrintJobDescriptionSequenceItemColl)
				{
					ReferencedPrintJobSequence objReferencedPrintJobSequence = objPrintJobDescriptionSequenceItem.getReferencedPrintJobSequence();

					ISingleCollection<ReferencedPrintJobSequenceItem> objReferencedPrintJobSequenceItemColl = (ISingleCollection<ReferencedPrintJobSequenceItem>)objReferencedPrintJobSequence.getValue();
					for(ReferencedPrintJobSequenceItem objTempReferencedPrintJobSequenceItem : objReferencedPrintJobSequenceItemColl)
					{
						if(objTempReferencedPrintJobSequenceItem.getReferencedSOPInstanceUID().equals(strValue))
						{
							objReferencedPrintJobSequenceItem = objTempReferencedPrintJobSequenceItem;
							break;
						}
					}
					if(objReferencedPrintJobSequenceItem != null)
						break;
				}
				if(objReferencedPrintJobSequenceItem != null)
				{
					if(objTagCollection != null)
					{
						for(ITag objITag : objTagCollection)
						{
							addDataElement(objITag.getGroupNumber(),objITag.getElementNumber(),objRstDataSet,objReferencedPrintJobSequenceItem);
						}
						objDataSetColl.add(objRstDataSet);
					}
					else
					{
						addDataElement(objRstDataSet,objReferencedPrintJobSequenceItem);
						objDataSetColl.add(objRstDataSet);
					}
					return EnumImplOpsStatus.SUCCESS.getValue();
				}
				else
				{
					if(DicomConfig.createInstance().isLoggingOn())
					{
						DicomLogger objDicomLogger =DicomLogger.getLogger();
						objDicomLogger.log(ResourceBundleWrapper.getValue("exceptions","NoInstanceCreated", new Locale(DicomConfig.createInstance().getLocale())) + enumRequestType);
					}
					return EnumImplOpsStatus.FAILURE.getValue();
				}
			}
			else
			{
				if(DicomConfig.createInstance().isLoggingOn())
				{
					DicomLogger objDicomLogger =DicomLogger.getLogger();
					objDicomLogger.log(ResourceBundleWrapper.getValue("exceptions","NoInstanceCreated", new Locale(DicomConfig.createInstance().getLocale())) + enumRequestType);
				}
				return EnumImplOpsStatus.FAILURE.getValue();
			}
		}
		default :
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger objDicomLogger =DicomLogger.getLogger();
				objDicomLogger.log(ResourceBundleWrapper.getValue("exceptions","ServiceRequestNotSupported", new Locale(DicomConfig.createInstance().getLocale())) + enumRequestType);
			}
			return EnumImplOpsStatus.FAILURE.getValue();
		}
		}
	}

	/**
	 * This function adds DaatElements to the resultant DataSet.
	 */
	private void addDataElement(IDataSet objRstDataSet, ReferencedPrintJobSequenceItem objReferencedPrintJobSequenceItem)
	{
		if(objRstDataSet.getTransferSyntax().getTransferSyntaxUID().equals(DicomConstants.TS_EXPLICIT_VR_LITTLE_ENDIAN) || 
				objRstDataSet.getTransferSyntax().getTransferSyntaxUID().equals(DicomConstants.TS_EXPLICIT_VR_BIG_ENDIAN))
		{
			for(IDataElement objIDataElement : objReferencedPrintJobSequenceItem)
			{
				IDataElement objTempDataElement =getExplicitDE(objIDataElement,objRstDataSet.getDictionaryReader());
				objRstDataSet.addDataElement(objTempDataElement);
			}
		}
		else
		{
			for(IDataElement objIDataElement : objReferencedPrintJobSequenceItem)
			{
				IDataElement objTempDataElement =getImplicitDE(objIDataElement,objRstDataSet.getDictionaryReader());
				objRstDataSet.addDataElement(objTempDataElement);
			}
		}
	}

	/**
	 * This function adds DaatElements to the resultant DataSet.
	 */
	private void addDataElement(int GroupNo, int ElementNo, IDataSet objRstDataSet, ReferencedPrintJobSequenceItem  objReferencedPrintJobSequenceItem)
	{

		if(objRstDataSet.getTransferSyntax().getTransferSyntaxUID().equals(DicomConstants.TS_EXPLICIT_VR_LITTLE_ENDIAN) || 
				objRstDataSet.getTransferSyntax().getTransferSyntaxUID().equals(DicomConstants.TS_EXPLICIT_VR_BIG_ENDIAN))
		{
			for(IDataElement objIDataElement : objReferencedPrintJobSequenceItem)
			{
				if(objIDataElement.getTag().getGroupNumber() == GroupNo && objIDataElement.getTag().getElementNumber() == ElementNo)
				{

					IDataElement objTempDataElement =getExplicitDE(objIDataElement,objRstDataSet.getDictionaryReader());
					objRstDataSet.addDataElement(objTempDataElement);
				}
			}
		}
		else
		{

			for(IDataElement objIDataElement : objReferencedPrintJobSequenceItem)
			{
				if(objIDataElement.getTag().getGroupNumber() == GroupNo && objIDataElement.getTag().getElementNumber() == ElementNo)
				{
					IDataElement objTempDataElement =getImplicitDE(objIDataElement,objRstDataSet.getDictionaryReader());
					objRstDataSet.addDataElement(objTempDataElement);
				}
			}
		}
	}

	private IDataElement getImplicitDE(IDataElement objIDataElement, IDictionaryReader objIDictionaryReader)
	{
		IDataElement objTempDataElement = new ImplicitDE(objIDataElement.getTag().getGroupNumber(), objIDataElement.getTag().getElementNumber(),objIDataElement.getValue(), new TransferSyntax(),objIDictionaryReader);
		return objTempDataElement;
	}

	private IDataElement getExplicitDE(IDataElement objIDataElement,IDictionaryReader objIDictionaryReader)
	{
		String strVR = objIDictionaryReader.getVR(objIDataElement.getTag().getGroupNumber(), objIDataElement.getTag().getElementNumber());
		int iVR = StandardMethods.getiVRtype(strVR);
		IDataElement objTempDataElement = new ExplicitDE(objIDataElement.getTag().getGroupNumber(), objIDataElement.getTag().getElementNumber(),iVR,objIDataElement.getValue());
		return objTempDataElement;
	}
}
