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

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


import cdac.medinfo.sdk.dcm30_04.baselibs.TransferSyntax;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IDataSet;
import cdac.medinfo.sdk.dcm30_04.commoninterface.ITransferSyntax;
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.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.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;

/**
 * This class provides functionality to query the data base and find 
 * the resultant matches depending on specified DataSet.
 */
public class MWLDataSourceImpl implements IDataSource  
{
	
	private MWLDBAgent objMWLAgent = null;

	/**
	 * Instantiates a new Data Source Implementation Class 
	 * @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 MWLDataSourceImpl(String strConnectionString, String strDriverName) throws SQLException,ClassNotFoundException, InstantiationException, IllegalAccessException 
	{
		objMWLAgent = MWLDBAgent.createInstance(strConnectionString, strDriverName);
	}

	/**
	 * 
	 * @return short - shows status value which will be used in generation of response
	 * 					Refer EnumImplOpsStatus for supported response status values.
	 */
	public short find(IQueryModel objQueryModel, IQueryModel objRstQueryModel)
	{
		ISingleCollection<IDataSet> objDataSetList = new SingleCollection<IDataSet>();
		ITransferSyntax objITransferSyntax = new TransferSyntax();
		objITransferSyntax.setTransferSyntax(DicomConstants.TS_DEFAULT_IMPLICIT_VR_LITTLE_ENDIAN);

		objQueryModel.encode(objITransferSyntax, objDataSetList);

		IDataSet objIDataSet = null;
		if(!objDataSetList.isEmpty())
		{
			objIDataSet = objDataSetList.get(0);

			DicomMessage objDicomMessage = new DicomMessage();
			objDicomMessage.setDataSet(objIDataSet);
	
			ISingleCollection<IDataSet> objRstDataCollection = new SingleCollection<IDataSet>();
			if(find(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();
	}

	/**
	 * 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(objMWLAgent.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();
	}

	/**
	 * @return short - shows status value which will be used in generation of response
	 * 					Refer EnumImplOpsStatus for supported response status values.
	 */
	public short retrieve(DicomMessage arg0, ISingleCollection<IDataSet> arg1)
	{
		return EnumImplOpsStatus.FAILURE.getValue();
	}
	
	/**
	 * Method unimplemented
	 */
	public short retrieve(IQueryModel arg0, IQueryModel arg1) {
		// TODO Auto-generated method stub
		return EnumImplOpsStatus.FAILURE.getValue();
	}
}
