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

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


import cdac.medinfo.sdk.dcm30_04.commoninterface.IDataSet;
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.dicomnetcommons.SinkException;
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.rtmachineverificationservice.dbhelper.RTMachineVerification_DBAgent;
import cdac.medinfo.sdk.dcm30_04.utils.DicomConfig;
import cdac.medinfo.sdk.dcm30_04.utils.DicomLogger;
import cdac.medinfo.sdk.dcm30_04.utils.ResourceBundleWrapper;
import cdac.medinfo.sdk.dcm30_04.utils.StandardMethods;

/**
 * RTMachineVerification_SinkImpl is the default implementation for DataSink of RT Machine Verification Class.<br>
 */
public class RTMachineVerification_SinkImpl implements IDataSink 
{
	private RTMachineVerification_DBAgent objRTMachineVerification_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 RTMachineVerification_SinkImpl(String strConnectionString, String strDriverName) throws SQLException,ClassNotFoundException, InstantiationException, IllegalAccessException
	{
		objRTMachineVerification_DBAgent = RTMachineVerification_DBAgent.createInstance(strConnectionString,strDriverName);
	}

	/**
	 * Populates the SOP Instance information in Database
	 * 
	 * @param objIDataSet instance of IDataSet
	 * @param strValue null in case of Study Management Service 
	 * @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)
			{
				EnumCommandField enumRequestType = objDicomMessage.getCommandType();
				
				String strSOPClassUID = null;
				ICommandSet objICommandSet = objDicomMessage.getCommandSet();
				if(enumRequestType == EnumCommandField.N_SET_RQ || enumRequestType == EnumCommandField.N_GET_RQ||enumRequestType == EnumCommandField.N_DELETE_RQ)
					strSOPClassUID = (String)objICommandSet.getValue(0x0000,0x0003);
				else if(enumRequestType == EnumCommandField.N_EVENT_REPORT_RQ || enumRequestType == EnumCommandField.N_CREATE_RQ)
					strSOPClassUID = (String)objICommandSet.getValue(0x0000,0x0002); // N_EVENT_REPORT
				
				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_INVALID_ATTRIBUTE_VALUE.getValue();
				}
				switch(enumRequestType)
					{
						case N_CREATE_RQ:
						{
							String strSOPInstance = objDicomMessage.getCommandSet().getValue(0x0000,0x1000).toString();
							IDataSet objIDataSet = objDicomMessage.getDataSet();
							if(isCreationAllowed(objIDataSet))
							{
								if(objRTMachineVerification_DBAgent.createRTMachineVerificationInstance(objIDataSet,strSOPInstance))
									return EnumImplOpsStatus.SUCCESS.getValue();
								else
									return EnumImplOpsStatus.FAILURE.getValue();
							}
							else
								return EnumImplOpsStatus.FAILURE_STEP_STATUS_CONFLICT.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();
							}
							
							if(isUpdationAllowed(strSOPInstance))
							{
								if(objRTMachineVerification_DBAgent.updateSOPInstance(objDicomMessage.getDataSet(),strSOPInstance))
									return EnumImplOpsStatus.SUCCESS.getValue();
								else
									return EnumImplOpsStatus.FAILURE.getValue();
							}
							else
								return EnumImplOpsStatus.FAILURE_STEP_STATUS_CONFLICT.getValue();
							
						}
						
						case N_DELETE_RQ :
						{
							String strSOPInstance = objDicomMessage.getCommandSet().getValue(0x0000,0x1001).toString();
							if(!objRTMachineVerification_DBAgent.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.getValue();
							}
							else
							{
								if(objRTMachineVerification_DBAgent.deleteSOPInstance(strSOPInstance))
								{
									return EnumImplOpsStatus.SUCCESS.getValue();
								}
								else
								{
									if(DicomConfig.createInstance().isLoggingOn())
									{
										DicomLogger objDicomLogger =DicomLogger.getLogger();
										objDicomLogger.log(ResourceBundleWrapper.getValue("exceptions","InstanceDeletionFailed", new Locale(DicomConfig.createInstance().getLocale())) + strSOPInstance);
									}
									return EnumImplOpsStatus.FAILURE.getValue();
								}
							}
						}

						default :
							return EnumImplOpsStatus.SUCCESS.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 the creation is allowed for the given DataSet.
	 * @param objIDataSet
	 * @return true/false
	 */
	private boolean isCreationAllowed(IDataSet objIDataSet) 
	{
		// TODO Auto-generated method stub
		return true;
	}

	/**
	 * Checks whether the updation is allowed for the given SOPInstanceUID.
	 * @param strSOPInstance
	 * @return true/false
	 * @throws SQLException
	 */
	private boolean isUpdationAllowed(String strSOPInstance)throws SQLException
	{
		try
		{
			return true;
		}
		catch (Exception e) 
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger objDicomLogger =DicomLogger.getLogger();
				objDicomLogger.log(e.getMessage());
			}	
		}
		return false;
	}


	/**
	 * Checks whether the  given SOPInstanceUID exists or not.
	 * @param strSOPInstance
	 * @return true/false
	 * @throws SQLException
	 */
	private boolean isSOPInstanceExist(String strSOPInstance)throws SQLException
	{
		return objRTMachineVerification_DBAgent.isSOPInstanceExist(strSOPInstance);
	}
	
	/**
	 * 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) 
	{
		return EnumImplOpsStatus.FAILURE.getValue();
	}
}