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



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.commoninterface.ITag;
import cdac.medinfo.sdk.dcm30_04.enums.EnumCommandField;
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.ICommandSet;
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.IDataSource;
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.ISingleCollection;
import cdac.medinfo.sdk.dcm30_04.utils.ResourceBundleWrapper;

/**
 * RTMachineVerification_SourceImpl is the default implementation for DataSource of RT  Machine Verification Class.<br>
 * This implementation provides the retrieval process for N-Get and N-Event Report service for RT  Machine Verification Class.<br>
 * It retrieves the SOPInstance and generates the Dataset accordingly and populates value only for queried attributes.<br>
 * It populates only first level DataElements as DICOM specifies that attributes of Sequence Item should not be queried.<br>
 * If an sequence attribute is queried then it populates all DataElements belonging to that Sequence. 
 */
public class RTMachineVerification_SourceImpl implements IDataSource 
{
	/** The obj db agent. */
	private RTMachineVerification_DBAgent objRTMachineVerification_DBAgent = null;

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

	/**
	 * Depending on the search attribute finds the matching DataSets and returns status.
	 * According to the matched DataSets populate the collection taken as out parameter.
	 * @param objRstDataSetCollection the obj rst data set collection
	 * @return short - shows status value which will be used in generation of response
	 * 					Refer EnumImplOpsStatus for supported response status values.
	 */
	public short find(DicomMessage objDicomMessage, ISingleCollection<IDataSet> objRstDataCollection) 
	{
		try 
		{
			if(objRTMachineVerification_DBAgent.find(objDicomMessage.getDataSet(), objRstDataCollection))
				return EnumImplOpsStatus.SUCCESS.getValue();
		}
		catch(SQLException sqle)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger objDicomLogger =DicomLogger.getLogger();
				objDicomLogger.log(sqle);
			}
			throw new SourceException(ResourceBundleWrapper.getValue("exceptions", "SQLException", new Locale(DicomConfig.createInstance().getLocale())), sqle);
		}
		catch (IOException ioe) 
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger objDicomLogger =DicomLogger.getLogger();
				objDicomLogger.log(ioe);
			}
			throw new SourceException(ResourceBundleWrapper.getValue("exceptions", "IOException", new Locale(DicomConfig.createInstance().getLocale())), ioe);

		}	
		catch (InvalidDataElementException ide)
		{
			if (DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger objDicomLogger = DicomLogger.getLogger();
				objDicomLogger.log(ide.getMessage());
			}
		}
		return EnumImplOpsStatus.NO_SUCH_OBJECT_INSTANCE.getValue();
	}

	/* (non-Javadoc)
	 * @see cdac.medinfo.sdk.dcm30_04.services.dimsecommons.IDataSource#find(cdac.medinfo.sdk.dcm30_04.services.dimsecommons.QueryModel, cdac.medinfo.sdk.dcm30_04.services.dimsecommons.QueryModel)
	 */
	/**
	 * Depending on the search attribute finds the matching DataSets and returns status. According to the matched DataSets populate the collection taken as out parameter.
	 */
	public short find(IQueryModel arg0, IQueryModel arg1) 
	{
		// TODO Auto-generated method stub
		return EnumImplOpsStatus.FAILURE.getValue();
	}

	/**
	 * Depending SOP Instance UID  finds the matching DataSets and returns status.
	 * According to the matched DataSets populate the collection taken as out parameter.
	 * @param objIDataSet The data set contains identifiers.
	 * @param objRstDataSetCollection the obj rst data set collection
	 * @return short - shows status value which will be used in generation of response
	 * 					Refer EnumImplOpsStatus for supported response status values.
	 */
	public short retrieve(DicomMessage objDicomMessage, ISingleCollection<IDataSet> objRstDatasetList)
	{
		try
		{
			if(objDicomMessage != null)
			{
				EnumCommandField enumRequestType = objDicomMessage.getCommandType();
				switch(enumRequestType)
				{
				case N_GET_RQ :
				{
					String strSOPInstance = null;
					ICommandSet objCommandSet = objDicomMessage.getCommandSet();
					if(objCommandSet.getValue(0x0000,0x1001) == null)
					{
						if(DicomConfig.createInstance().isLoggingOn())
						{
							DicomLogger objDicomLogger =DicomLogger.getLogger();
							objDicomLogger.log(ResourceBundleWrapper.getValue("warning","SOPInstanceUIDNotProvided", new Locale(DicomConfig.createInstance().getLocale())) + strSOPInstance);
						}
						return EnumImplOpsStatus.FAILURE_NO_SUCH_OBJECT_INSTANCE.getValue();
					}
					else
					{
						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();
					}
					ISingleCollection<ITag> objTagCollection = (ISingleCollection<ITag>)objDicomMessage.getCommandSet().getValue(0x0000,0x1005);
					IDataSet objIDataSet = objRTMachineVerification_DBAgent.retrieveRTMachineVerificationInstanceInfo(objTagCollection, strSOPInstance);
					
					if(objIDataSet != null)
					{
						objRstDatasetList.add(objIDataSet);
						return EnumImplOpsStatus.SUCCESS.getValue();
					}
					else
						return EnumImplOpsStatus.FAILURE_NO_SUCH_OBJECT_INSTANCE.getValue();
					}
				case N_EVENT_REPORT_RQ:
				{
					String strSOPInstance = null;
					ICommandSet objCommandSet = objDicomMessage.getCommandSet();
					if(objCommandSet.getValue(0x0000,0x1000) == null)
					{
						if(DicomConfig.createInstance().isLoggingOn())
						{
							DicomLogger objDicomLogger =DicomLogger.getLogger();
							objDicomLogger.log(ResourceBundleWrapper.getValue("warning","SOPInstanceUIDNotProvided", new Locale(DicomConfig.createInstance().getLocale())) + strSOPInstance);
						}
						return EnumImplOpsStatus.FAILURE_NO_SUCH_OBJECT_INSTANCE.getValue();
					}
					else
					{
						strSOPInstance = objDicomMessage.getCommandSet().getValue(0x0000,0x1000).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();
					}
					ISingleCollection<ITag> objTagCollection = (ISingleCollection<ITag>)objDicomMessage.getCommandSet().getValue(0x0000,0x1005);
					IDataSet objIDataSet = objRTMachineVerification_DBAgent.checkRTMachineVerificationStatus(objTagCollection, strSOPInstance);
					
					if(objIDataSet != null)
					{
						objRstDatasetList.add(objIDataSet);
						return EnumImplOpsStatus.SUCCESS.getValue();
					}
					else
						return EnumImplOpsStatus.FAILURE_NO_SUCH_OBJECT_INSTANCE.getValue();
					}					
				}
			}
		}
		catch(SQLException sql)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger objDicomLogger =DicomLogger.getLogger();
				objDicomLogger.log(sql.getMessage());
			}
			throw new SourceException(ResourceBundleWrapper.getValue("exceptions", "SQLException", new Locale(DicomConfig.createInstance().getLocale())), sql);
		}
		catch (InvalidDataElementException ide)
		{
			if (DicomConfig.createInstance().isLoggingOn())
			{
			    DicomLogger objDicomLogger = DicomLogger.getLogger();
			    objDicomLogger.log(ide.getMessage());
			}
		}
		return EnumImplOpsStatus.FAILURE.getValue();
	}
	/**
	 * Depending SOP Instance UID  finds whether that instance exists or not.
	 * @return boolean -  whether that instance exists or not.
	 */
	private boolean isSOPInstanceExist(String strSOPInstance)throws SQLException
	{
		return objRTMachineVerification_DBAgent.isSOPInstanceExist(strSOPInstance);
	}

	@Override
	/**
	 * Depending SOP Instance UID  finds the matching DataSets and returns status. According to the matched DataSets populate the collection taken as out parameter.
	 */
	public short retrieve(IQueryModel objQueryModel, IQueryModel objRstQueryModel)
	{
		return EnumImplOpsStatus.FAILURE.getValue();
	}
}
