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

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.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.ICommandElement;
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.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.IDataSource;
import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.IQueryModel;
import cdac.medinfo.sdk.dcm30_04.services.displaysystemmanagement.dbhelper.DisplaySystem_DBAgent;
import cdac.medinfo.sdk.dcm30_04.utils.DicomConfig;
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;
/**
 * DisplaySystem_SourceImpl is the default implementation for DataSource implementation for Display System Management Service Class.<br>
 * This implementation handles N-Get  queries for Display System.
 * In NGet 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 DisplaySystem_SourceImpl implements IDataSource  
{
	
	/** The obj db agent. */
	private DisplaySystem_DBAgent objDisplaySystem_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 DisplaySystem_SourceImpl(String strConnectionString, String strDriverName) throws SQLException, IllegalAccessException,InstantiationException,ClassNotFoundException
	{
		objDisplaySystem_DBAgent = DisplaySystem_DBAgent.createInstance(strConnectionString,strDriverName);
	}

	/*(non-Javadoc)
	 * @see cdac.medinfo.sdk.dcm30_04.services.dimsecommons.IDataSource#find(cdac.medinfo.sdk.dcm30_04.commoninterface.IDataSet, cdac.medinfo.sdk.dcm30_04.utils.ISingleCollection)
	 */
	public short find(DicomMessage objDicomMessage, ISingleCollection<IDataSet> arg1) {
		// TODO Auto-generated method stub
		return EnumImplOpsStatus.FAILURE.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)
	 */
	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 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
		{
			if(objDicomMessage != null)
			{
				EnumCommandField enumRequestType = objDicomMessage.getCommandType();

				String strSOPInstance = objDicomMessage.getCommandSet().getValue(0x0000,0x1001).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 = objDisplaySystem_DBAgent.retrieveDisplaySystemInstanceInfo(objTagCollection, strSOPInstance);
					if(objIDataSet != null)
					{
						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());
			}
		}
		return EnumImplOpsStatus.FAILURE.getValue();
	}
	/**
	 * Checks if  SOP Instance UID  exists or not.
	 * @param strSOPInstance SOP Instance UID
	 * @return boolean - True or False
	 */
	private boolean isSOPInstanceExist(String strSOPInstance)throws SQLException
	{
		return objDisplaySystem_DBAgent.isSOPInstanceExist(strSOPInstance);
	}
	/**
	 * Depending SOP Instance UID  finds the matching DataSets and returns status.
	 * According to the matched DataSets populate the collection taken as out parameter.
	 * @param objQueryModel The Query Model containing identifiers.
	 * @param objRstQueryModel the obj rst Query Model collection
	 * @return short - shows status value which will be used in generation of response
	 * 					Refer EnumImplOpsStatus for supported response status values.
	 */
	public short retrieve(IQueryModel objQueryModel, IQueryModel objRstQueryModel) 
	{
		DicomMessage objDicomMessage = new DicomMessage();
		ICommandSet objICommandSet = null;
		if(objQueryModel instanceof NGetDisplaySystemManagement_QueryModel)
		{
			objICommandSet = new CommandSet(); 
			
			NGetDisplaySystemManagement_QueryModel objNGetDisplaySystemManagementQueryModel = (NGetDisplaySystemManagement_QueryModel)objQueryModel;
			
			// set Command field
			ICommandElement objICommandElement = new CommandElement(0x0000,0x0100,EnumCommandField.N_GET_RQ.getValue()); 
			objICommandSet.addCommandElement(objICommandElement);

			// set Requested SOP Instance
			String strReqSOPInsUID = objNGetDisplaySystemManagementQueryModel.getReqSOPInsUID();
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger objDicomLogger = DicomLogger.getLogger();
				objDicomLogger.log(ResourceBundleWrapper.getValue("status","NGet.InstanceSet",new Locale(DicomConfig.createInstance().getLocale()))+ strReqSOPInsUID);
			}
			if(strReqSOPInsUID == null)
			{
				if(DicomConfig.createInstance().isLoggingOn())
				{
					DicomLogger objDicomLogger =DicomLogger.getLogger();
					objDicomLogger.log(ResourceBundleWrapper.getValue("exceptions","InvalidValue", new Locale(DicomConfig.createInstance().getLocale())) + strReqSOPInsUID);
				}
				return EnumImplOpsStatus.FAILURE_INVALID_ATTRIBUTE_VALUE.getValue();
			}
			ICommandElement objICEReqSOPInst = new CommandElement(0x0000,0x1001,strReqSOPInsUID);
			objICommandSet.addCommandElement(objICEReqSOPInst);
			
			// Set Requested SOP CLass UID
			ICommandElement objICEReqSOPClass = new CommandElement(0x0000, 0x0003,EnumSOPClassUIDs.MEDIACREATIONMANAGEMENT.getValue());
			objICommandSet.addCommandElement(objICEReqSOPClass);
			
			//Set optional Field - Attribute Identifier List
			ISingleCollection<ITag> objTagColl = objNGetDisplaySystemManagementQueryModel.getTagCollection();
			if(objTagColl != null)
			{
				ICommandElement objICEAttributeIdentifierList = new CommandElement(0x0000,0x1005,objTagColl);
				objICommandSet.addCommandElement(objICEAttributeIdentifierList);
			}
			
			//Set Command Set to DicomMessage
			objDicomMessage.setCommandSet(objICommandSet);
			
			ISingleCollection<IDataSet> objRstDataCollection = new SingleCollection<IDataSet>();
			if(retrieve(objDicomMessage, objRstDataCollection) == EnumImplOpsStatus.SUCCESS.getValue())
			{
				ICollectionIterator<IDataSet> objDataSetColl = objRstDataCollection.iterator();
				while(objDataSetColl.hasNext())
				{
					IDataSet objRstDataSet = objDataSetColl.next();
					objRstQueryModel.decode(objRstDataSet);
				}
				return EnumImplOpsStatus.SUCCESS.getValue();
			}
			else
				return EnumImplOpsStatus.FAILURE.getValue();	
		}
		else 
			return EnumImplOpsStatus.FAILURE.getValue();
	}
}
