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

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


import cdac.medinfo.sdk.dcm30_04.baselibs.TransferSyntax;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IDataSet;
import cdac.medinfo.sdk.dcm30_04.commoninterface.ITransferSyntax;
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.ICommandElement;
import cdac.medinfo.sdk.dcm30_04.services.dicomnetcommons.ICommandSet;
import cdac.medinfo.sdk.dcm30_04.services.dicomnetcommons.SinkException;
import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.CommandElement;
import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.CommandSet;
import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.DicomMessage;
import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.IDataSink;
import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.IQueryModel;
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.SingleCollection;
import cdac.medinfo.sdk.dcm30_04.utils.StandardMethods;

/**
 * PrintDataSinkImpl is the default implementation for DataSink implementation for Print Management Service Class.<br>
 * This implementation provides the implementation of Creation, Updation and deletion for all the SOP Classses supported for Print Management Service.<br>
 * Creation ,Updation and deletion process use the provided SOPInstance UID and processes the request accordingly.<br>
 * In case of updation it updates the first level DataElements.<br>
 * For SQ elements it replaces the all entries belonging to that SQ by new information provided.  
 */
public class PrintDataSinkImpl implements IDataSink 
{
	private Print_DBAgent objPrint_DBAgent = null;

	/**
	 * Instantiates a new data sink impl.
	 * @param strConnectionString the str connection string
	 * @param strDriverName the str driver name
	 * @throws SQLException the SQL exception
	 * @throws ClassNotFoundException the class not found exception
	 * @throws InstantiationException the instantiation exception
	 * @throws IllegalAccessException the illegal access exception
	 */
	public PrintDataSinkImpl(String strConnectionString, String strDriverName) throws SQLException,ClassNotFoundException, InstantiationException, IllegalAccessException
	{
		objPrint_DBAgent = Print_DBAgent.createInstance(strConnectionString,strDriverName);
	}


	/**
	 * Populates , updates and deletes the SOP Instance information in Database
	 * @param objIDataSet instance of IDataSet
	 * @param strValue SOP instance value which is to be created , updated or deleted.
	 * @return short - shows status value which will be used in generation of response
	 * 				Refer EnumImplOpsStatus for supported response status values.
	 */
	public short store(DicomMessage objDicomMessage, String strValue)
	{
		try
		{
			if(objDicomMessage != null)
			{
				String strSOPClassUID = null;
				EnumCommandField enumRequestType = objDicomMessage.getCommandType();
				ICommandSet objCommandSet = objDicomMessage.getCommandSet();
				if(enumRequestType.equals(EnumCommandField.N_SET_RQ) || enumRequestType.equals(EnumCommandField.N_DELETE_RQ) || enumRequestType.equals(EnumCommandField.N_ACTION_RQ))
					strSOPClassUID = (String)objCommandSet.getValue(0x0000,0x0003);
				else
					strSOPClassUID = (String)objCommandSet.getValue(0x0000,0x0002);
				EnumSOPClassUIDs enumSOPClassUIDs = StandardMethods.getSOPClassUID(strSOPClassUID);
				if(enumSOPClassUIDs == null)
				{
					if(DicomConfig.createInstance().isLoggingOn())
					{
						DicomLogger objDicomLogger = DicomLogger.getLogger();
						objDicomLogger.log(ResourceBundleWrapper.getValue("exceptions","UnknownSOPClassUID",new Locale(DicomConfig.createInstance().getLocale()))+ strSOPClassUID);
					}
					return EnumImplOpsStatus.FAILURE.getValue();
				}

				switch(enumSOPClassUIDs)
				{
				case BASICFILMSESSIONIOD :
				{
					BasicFilmSessionDataSinkImpl objBasicFilmSessionImpl = new BasicFilmSessionDataSinkImpl();
					return objBasicFilmSessionImpl.store(objPrint_DBAgent, objDicomMessage, strValue);
				}
				case BASICFILMBOXIOD :
				{
					BasicFilmBoxDataSinkImpl objBasicFilmBoxImpl = new BasicFilmBoxDataSinkImpl();
					return objBasicFilmBoxImpl.store(objPrint_DBAgent, objDicomMessage, strValue);
				}
				case BASICGRAYSCALEIMAGEBOX :
				{
					ImageBoxDataSinkImpl objImageBoxSOPClassImpl = new ImageBoxDataSinkImpl();
					return objImageBoxSOPClassImpl.storeBasicGrayScale(objPrint_DBAgent, objDicomMessage, strValue);
				}
				case BASICCOLORIMAGEBOX :
				{
					ImageBoxDataSinkImpl objImageBoxSOPClassImpl = new ImageBoxDataSinkImpl();
					return objImageBoxSOPClassImpl.storeBasicColorImage(objPrint_DBAgent, objDicomMessage, strValue);
				}
				case PRESENTATIONLUTIOD :
				{
					PresentationLUTDataSinkImpl objPresentationLUTImpl = new PresentationLUTDataSinkImpl();
					return objPresentationLUTImpl.store(objPrint_DBAgent, objDicomMessage, strValue);
				}
				case BASICPRINTIMAGEOVERLAYBOXIOD :
				{
					BasicPrintImageOverlayDataSinkImpl objBasicPrintImageOverlayImpl = new BasicPrintImageOverlayDataSinkImpl();
					return objBasicPrintImageOverlayImpl.store(objPrint_DBAgent, objDicomMessage, strValue);
				}
				case BASICANNOTATIONBOX :
				{
					BasicAnnotationDataSinkImpl objBasicAnnotationImpl = new BasicAnnotationDataSinkImpl();
					return objBasicAnnotationImpl.store(objPrint_DBAgent, objDicomMessage, strValue);
				}
				case PRINTQUEUEMANAGEMENTIOD :
				{
					PrintQueueManagementSinkImpl objPrintQueueManagementSinkImpl = new PrintQueueManagementSinkImpl();
					return objPrintQueueManagementSinkImpl.store(objPrint_DBAgent, objDicomMessage, strValue);
				}
				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();
				}
				}
			}
			else
			{
				if(DicomConfig.createInstance().isLoggingOn())
				{
					DicomLogger objDicomLogger =DicomLogger.getLogger();
					objDicomLogger.log(ResourceBundleWrapper.getValue("exceptions","StorageFalied", new Locale(DicomConfig.createInstance().getLocale())));
				}
				return EnumImplOpsStatus.FAILURE.getValue();
			}
		}
		catch(IOException ioe)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger objDicomLogger =DicomLogger.getLogger();
				objDicomLogger.log(ioe.getMessage());
			}
			throw new SinkException(ResourceBundleWrapper.getValue("exceptions", "IOException", new Locale(DicomConfig.createInstance().getLocale())), ioe);
		}
		catch(SQLException sql)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger objDicomLogger =DicomLogger.getLogger();
				objDicomLogger.log(sql.getMessage());
			}
			throw new SinkException(ResourceBundleWrapper.getValue("exceptions", "SQLException", new Locale(DicomConfig.createInstance().getLocale())), sql);
		}
	}


	/**
	 * Stores,Creates or Sets the instance in DataBase if available from given Query Model.
	 * @param objQueryModel Instance of Query Model to be stored or created.
	 * @param strValue string value of Data Base storage path in store request, or Affected SOP Instance UID
	 * 				   in case of NCreate, or Requested SOP Instance UID in case of NSet request.  
	 * @return short - shows status value which will be used in generation of response
	 * 				   Refer EnumImplOpsStatus for supported response status values.
	 */
	public short store(IQueryModel objQueryModel, String strValue)
	{
		ISingleCollection<IDataSet> objDataSetList = new SingleCollection<IDataSet>();
		ITransferSyntax objITransferSyntax = new TransferSyntax();
		objITransferSyntax.setTransferSyntax(DicomConstants.TS_DEFAULT_IMPLICIT_VR_LITTLE_ENDIAN);

		objQueryModel.encode(objITransferSyntax, objDataSetList);

		IDataSet objIDataSet = objDataSetList.get(0);

		DicomMessage objDicomMessage = new DicomMessage();
		objDicomMessage.setDataSet(objIDataSet);
		
		ICommandSet objICommandSet = new CommandSet();
		if(objQueryModel instanceof NCreateImagePrintMangMeta_QueryModel)
		{
			// set Command field
			ICommandElement objICommandElement = new CommandElement(0x0000,0x0100,EnumCommandField.N_CREATE_RQ.getValue()); 
			objICommandSet.addCommandElement(objICommandElement);

			// set Affected SOP Instance
			if(strValue == null)
				strValue = StandardMethods.generateUUID();
				
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger objDicomLogger = DicomLogger.getLogger();
				objDicomLogger.log(ResourceBundleWrapper.getValue("status","NCreate.InstanceCreated",new Locale(DicomConfig.createInstance().getLocale()))+ strValue);
			}
			
			ICommandElement objICEAffSOPInst = new CommandElement(0x0000,0x1000,strValue);
			objICommandSet.addCommandElement(objICEAffSOPInst);
			
			// Set Affected SOP CLass UID
			EnumSOPClassUIDs enumSOPClassUIDs = ((NCreateImagePrintMangMeta_QueryModel) objQueryModel).getEnumSOPClassUIDs();
			ICommandElement objICEAffSOPClass = new CommandElement(0x0000, 0x0002,enumSOPClassUIDs.getValue());
			objICommandSet.addCommandElement(objICEAffSOPClass);
		}
		else if(objQueryModel instanceof NSetImagePrintMangMeta_QueryModel)
		{
			// set Command field
			ICommandElement objICommandElement = new CommandElement(0x0000,0x0100,EnumCommandField.N_SET_RQ.getValue()); 
			objICommandSet.addCommandElement(objICommandElement);

			// set Requested SOP Instance
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger objDicomLogger = DicomLogger.getLogger();
				objDicomLogger.log(ResourceBundleWrapper.getValue("status","NSet.InstanceSet",new Locale(DicomConfig.createInstance().getLocale()))+ strValue);
			}
			
			if(strValue == null)
			{
				if(DicomConfig.createInstance().isLoggingOn())
				{
					DicomLogger objDicomLogger =DicomLogger.getLogger();
					objDicomLogger.log(ResourceBundleWrapper.getValue("exceptions","InvalidValue", new Locale(DicomConfig.createInstance().getLocale())) + strValue);
				}
				return EnumImplOpsStatus.FAILURE_INVALID_ATTRIBUTE_VALUE.getValue();
			}
			
			ICommandElement objICEReqSOPInst = new CommandElement(0x0000,0x1001,strValue);
			objICommandSet.addCommandElement(objICEReqSOPInst);
			
			// Set Requested SOP CLass UID
			EnumSOPClassUIDs enumSOPClassUIDs = ((NSetImagePrintMangMeta_QueryModel) objQueryModel).getEnumSOPClassUIDs();
			ICommandElement objICEReqSOPClass = new CommandElement(0x0000, 0x0003,enumSOPClassUIDs.getValue());
			objICommandSet.addCommandElement(objICEReqSOPClass);
		}

		objDicomMessage.setCommandSet(objICommandSet);

		return store(objDicomMessage, null);
	}
}
