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

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.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.enums.EnumCommandField;
import cdac.medinfo.sdk.dcm30_04.exceptions.InvalidDataElementException;
import cdac.medinfo.sdk.dcm30_04.exceptions.ParseException;
import cdac.medinfo.sdk.dcm30_04.services.dicomnetcommons.EnumImplOpsStatus;
import cdac.medinfo.sdk.dcm30_04.services.dicomnetcommons.EnumNEventReportStatus;
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.ups.dbhelper.UPSDBAgent;
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;
/**
 * UPS_SourceImpl is the default implementation for DataSource implementation for Unified Procedure Step Service Class.<br>
 * This implementation handles N-Services  queries for UPS.
 * In N-Services 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 any sequence attribute is queried then it populates all DataElements belonging to that Sequence. 
 */


public class UPS_SourceImpl implements IDataSource  {

	/**
	 * This id default constructor for UPS_SourceImpl
	 */
	public UPS_SourceImpl() {
		super();
	}
	/** The obj db agent. */
	private UPSDBAgent objUPSDBAgent = 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 UPS_SourceImpl(String strConnectionString, String strDriverName) throws SQLException, IllegalAccessException,InstantiationException,ClassNotFoundException
	{
		objUPSDBAgent = UPSDBAgent.createInstance(strConnectionString,strDriverName);
	}

	/**
	 * Depending on the keys present in DataSet of DicomMEssage it finds the matching DataSets and returns status.
	 * According to the matched DataSets populate the collection taken as out parameter.
	 * @param objDicomMessage  instance of DicomMessage whose Dataset to be stored in Database.
	 * @param objRstDataCollection collection of Resultant DataSet
	 * @return short - shows status value which will be used in generation of response
	 * 					Refer EnumImplOpsStatus for supported response status values.
	 * @throws SQLException - thrown in case of database access error or other errors.
	 */
	public short find(DicomMessage objDicomMessage, ISingleCollection<IDataSet> objRstDataCollection) 
	{
		try 
		{
			if(objUPSDBAgent.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.FAILURE.getValue();
	}

	
	/**
	 * Unimplemented method.
	 */
	public short find(IQueryModel arg0, IQueryModel arg1) {
		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 containing 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.
	 */
	@SuppressWarnings("unchecked")
	public short retrieve(DicomMessage objDicomMessage, ISingleCollection<IDataSet> objRstDatasetList)
	{
		try
		{
			String strSOPInstance = null ;
			if(objDicomMessage != null)
			{
				EnumCommandField enumRequestType = objDicomMessage.getCommandType();
				if(enumRequestType.toString().equals("N_GET_RQ"))
				strSOPInstance = objDicomMessage.getCommandSet().getValue(0x0000,0x1001).toString();
				else 
					strSOPInstance = objDicomMessage.getValue(0x0000,0x1000).toString();
				//checking whether this sop instance has been created or not.
				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();
				}
				switch(enumRequestType)
				{
				case N_GET_RQ :
				{
					ISingleCollection<ITag> objTagCollection = (ISingleCollection<ITag>)objDicomMessage.getCommandSet().getValue(0x0000,0x1005);

					IDataSet objIDataSet = objUPSDBAgent.retrieveUPSInstanceInfo(objTagCollection, strSOPInstance);
					if(objIDataSet != null)
					{
						objIDataSet.removeDataElement(getDataElement(0x0008,0x1195, null, objIDataSet.getDictionaryReader()));
						objRstDatasetList.add(objIDataSet);
						return EnumImplOpsStatus.SUCCESS.getValue();
					}
					else
						return EnumImplOpsStatus.FAILURE_NO_SUCH_OBJECT_INSTANCE.getValue();
				}
				case N_EVENT_REPORT_RQ :
				{
					IDataSet objIDataSet = null ;
					ISingleCollection<ITag> objTagCollection = (ISingleCollection<ITag>)objDicomMessage.getCommandSet().getValue(0x0000,0x1005);
					
					strSOPInstance = objDicomMessage.getCommandSet().getValue(0x0000,0x1000).toString();
					String eventID = objDicomMessage.getCommandSet().getDataForTag(0x0000, 0x1002).getDicomValue().toString() ;
					if(!checkForSubscription(strSOPInstance))
					{
						if(DicomConfig.createInstance().isLoggingOn())
						{
							DicomLogger objDicomLogger =DicomLogger.getLogger();
							objDicomLogger.log(ResourceBundleWrapper.getValue("exceptions","ServiceRequestNotSupported", new Locale(DicomConfig.createInstance().getLocale())) + enumRequestType);
						}
						return EnumNEventReportStatus.UPS_STATE_WAS_NOT_SCHEDULED.getValue();
						
					}
					if(eventID.equals("1"))
					{
						objIDataSet = objUPSDBAgent.retrieveUPSInstanceInfo(objTagCollection, strSOPInstance);
					}
					else if(eventID.equals("2"))
					{
						objIDataSet = objUPSDBAgent.retrieveUPSInstanceInfoForTwo(objTagCollection, strSOPInstance);
					}
					else if(eventID.equals("3"))
					{
						objIDataSet = objUPSDBAgent.retrieveUPSInstanceInfoForThree(objTagCollection, strSOPInstance);
					}
					else if(eventID.equals("4"))
					{
						objIDataSet = objUPSDBAgent.retrieveUPSInstanceInfo(objTagCollection, strSOPInstance);
					}
					
					if(objIDataSet != null)
					{
						objIDataSet.removeDataElement(getDataElement(0x0008,0x1195, null, objIDataSet.getDictionaryReader()));
						objRstDatasetList.add(objIDataSet);
						return EnumImplOpsStatus.SUCCESS.getValue();
					}
					else
						return EnumImplOpsStatus.FAILURE_NO_SUCH_OBJECT_INSTANCE.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();
				}
				}
			}
		}
		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());
			}
		} catch (ParseException e) {
			if (DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger objDicomLogger = DicomLogger.getLogger();
				objDicomLogger.log(e.getMessage());
			}
		}
		return EnumImplOpsStatus.FAILURE.getValue();
	}
	/**
	 * Checks whether provided SOP Instance UID is Subscription 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 checkForSubscription(String strSOPInstance) throws SQLException
	{
		return objUPSDBAgent.checkForSubscription(strSOPInstance);
	}
	/**
	 * 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);
	}

	@Override
	/**
	 * Unimplemented method.s
	 */
	public short retrieve(IQueryModel arg0, IQueryModel arg1) {
		return 0;
	}
	/**
	 * 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;
	}

}
