/*******************************************************************************
 *  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.ups.sinkimpl;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Locale;


import cdac.medinfo.sdk.dcm30_04.baselibs.ImplicitDE;
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.ITransferSyntax;
import cdac.medinfo.sdk.dcm30_04.enums.EnumCommandField;
import cdac.medinfo.sdk.dcm30_04.enums.EnumSOPClassUIDs;
import cdac.medinfo.sdk.dcm30_04.exceptions.InvalidDataElementException;
import cdac.medinfo.sdk.dcm30_04.services.dicomnetcommons.EnumImplOpsStatus;
import cdac.medinfo.sdk.dcm30_04.services.dicomnetcommons.EnumNActionStatus;
import cdac.medinfo.sdk.dcm30_04.services.dicomnetcommons.EnumNSetStatus;
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.dicomnetcommons.SourceException;
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.IDataSource;
import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.IQueryModel;
import cdac.medinfo.sdk.dcm30_04.services.ups.dbhelper.UPSDBAgent;
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.ICollectionIterator;
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;

/**
 * UPSIDataSinkImpl is the default implementation for DataSink implementation for UPS Service Class.<br>
 * This implementation provides the implementation of Creation, Updation and deletion for all the SOP Classes 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 UPSIDataSinkImpl implements IDataSink  
{


	private UPSDBAgent objUPSDBAgent = null;

	/**
	 * Instantiates a new data sink impl.
	 * @param strConnectionString the string connection string
	 * @param strDriverName the string 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 UPSIDataSinkImpl(String strConnectionString, String strDriverName) throws SQLException,ClassNotFoundException, InstantiationException, IllegalAccessException
	{
		objUPSDBAgent = UPSDBAgent.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
		{
			IDataSet objIDataSet = objDicomMessage.getDataSet();
			IDictionaryReader objDictionaryReader = objIDataSet.getDictionaryReader();
		
			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(enumRequestType)
				{
				case N_ACTION_RQ : 
					if(objDicomMessage.getDataSet().isPresent(0x0074,0x1234))
					{
						if(	objUPSDBAgent.storeInstanceInfoForSubscription(objDicomMessage.getDataSet()))
						{
							return EnumImplOpsStatus.SUCCESS.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();
						}
					}
					if(objDicomMessage.getDataSet().isPresent(0x0008,0x00018))
					{
						if(	objUPSDBAgent.storeInstanceInfoForUnsubscribe(objDicomMessage.getDataSet()))
						{
							return EnumImplOpsStatus.SUCCESS.getValue();
						}
						else
						{
							if(DicomConfig.createInstance().isLoggingOn())
							{
								DicomLogger objDicomLogger =DicomLogger.getLogger();
								objDicomLogger.log(ResourceBundleWrapper.getValue("exceptions","StorageFalied", new Locale(DicomConfig.createInstance().getLocale())));
							}
							return EnumNActionStatus.SOP_INSTANCE_UID_DOES_NOT_EXIST_OR_IS_NOT_A_UPS_INSTANCE_MANAGED_BY_THIS_SCP.getValue();
						}
					}
					if(	objUPSDBAgent.storeInstanceInfoForCancle(objDicomMessage.getDataSet()))
					{
						return EnumImplOpsStatus.SUCCESS.getValue();
					}
					else
					{
						if(DicomConfig.createInstance().isLoggingOn())
						{
							DicomLogger objDicomLogger =DicomLogger.getLogger();
							objDicomLogger.log(ResourceBundleWrapper.getValue("exceptions","StorageFalied", new Locale(DicomConfig.createInstance().getLocale())));
						}
						return EnumNActionStatus.UPS_IS_ALREADY_IN_THE_REQUESTED_STATE_OF_CANCELED.getValue();
					}

				case N_SET_RQ : 

					String strSOPInstance =objDicomMessage.getCommandSet().getValue(0x0000,0x1001).toString();	
					
					if(!isSOPInstanceExist(strSOPInstance))
					{
						if(DicomConfig.createInstance().isLoggingOn())
						{
							DicomLogger objDicomLogger =DicomLogger.getLogger();
							objDicomLogger.log(ResourceBundleWrapper.getValue("exceptions","NoInstanceCreated", new Locale(DicomConfig.createInstance().getLocale())) + strSOPInstance);
						}
						return EnumImplOpsStatus.FAILURE_NO_SUCH_OBJECT_INSTANCE.getValue();
					}
					
					else
					{
						if(objUPSDBAgent.updateSOPInstance(objDicomMessage.getDataSet(),strSOPInstance))
							return EnumImplOpsStatus.SUCCESS.getValue();
						else
							return EnumImplOpsStatus.FAILURE.getValue();
					}

				case N_CREATE_RQ :
				{
					objIDataSet.addDataElement( getDataElement(0x0008,0x0016,strSOPClassUID,objDictionaryReader));
					objIDataSet.addDataElement( getDataElement(0x0008,0x0018,(String)objCommandSet.getValue(0x0000,0x1000),objDictionaryReader));
					objIDataSet.addDataElement(getDataElement(0x0074,0x1000,"SCHEDULED" , objDictionaryReader)); 
					if(	objUPSDBAgent.storeInstanceInfo(objIDataSet))
					{
						return EnumImplOpsStatus.SUCCESS.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);
		}
		return EnumImplOpsStatus.FAILURE.getValue();	
	}

	@Override
	/**
	 * UnImplemented method.
	 */
	public short store(IQueryModel arg0, String arg1) throws SinkException {
		return 0;
	}

	/**
	 * 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 storeForCancle(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();
				}
				if(	objUPSDBAgent.storeInstanceInfo(objDicomMessage.getDataSet()))
				{
					return EnumImplOpsStatus.SUCCESS.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);
		}
		return EnumImplOpsStatus.FAILURE.getValue();	
	}

	/**
	 * Checks whether provided Transaction UID is created or not.
	 * @param strSOPInstance value of SOP Instance UID 
	 * @return boolean shows status as success or failure
	 * @throws SQLException if sql operation fails
	 */
	private boolean isTransactionUIDExist(String strUID)throws SQLException
	{
		return objUPSDBAgent.isTransactionUIDExist(strUID);
	}
	/**
	 * Checks whether provided SOP Instance UID is created or not.
	 * @param strSOPInstance value of SOP Instance UID 
	 * @return boolean shows status as success or failure
	 * @throws SQLException if sql operation fails
	 */
	private boolean isSOPInstanceExist(String strSOPInstance)throws SQLException
	{
		return objUPSDBAgent.isSOPInstanceExist(strSOPInstance);
	}
	
	/**
	 * 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;
	}
}

