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

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.enums.EnumCommandField;
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.SinkException;
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.IDataSink;
import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.IQueryModel;
import cdac.medinfo.sdk.dcm30_04.services.mediacreation.dbhelper.MediaCreation_DBAgent;
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.EnumFeatureList;
import cdac.medinfo.sdk.dcm30_04.utils.ISingleCollection;
import cdac.medinfo.sdk.dcm30_04.utils.ResourceBundleWrapper;
import cdac.medinfo.sdk.dcm30_04.utils.SingleCollection;
import cdac.medinfo.sdk.dcm30_04.utils.StandardMethods;

/**
 * MediaCreation_SinkImpl is the default implementation for Media Creation Management Service Class.<br>
 * This implementation provides the creation process of Media Creation Management SOP Class for N-Create service.<br>
 * SOP Instance Creation operation uses the provided SOPInstance UID and processes the request accordingly.<br>
 */
public class MediaCreation_SinkImpl implements IDataSink 
{
	private MediaCreation_DBAgent objMediaCreation_DBAgent = null;

	/**
	 * Instantiates a new data sink implementation.
	 * @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 MediaCreation_SinkImpl(String strConnectionString, String strDriverName) throws SQLException,ClassNotFoundException, InstantiationException, IllegalAccessException
	{
		objMediaCreation_DBAgent = MediaCreation_DBAgent.createInstance(strConnectionString,strDriverName);
	}

	/**
	 * Populates the SOP Instance information in Database
	 * 
	 * @param objIDataSet instance of IDataSet
	 * @param strValue null in case of Media Creation.
	 * @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();
				switch(enumRequestType)
				{
				case N_CREATE_RQ :
				{
					String strSOPInstance = objDicomMessage.getCommandSet().getValue(0x0000,0x1000).toString();
					if(isSOPInstanceExist(strSOPInstance))
					{
						if(DicomConfig.createInstance().isLoggingOn())
						{
							DicomLogger objDicomLogger =DicomLogger.getLogger();
							objDicomLogger.log(ResourceBundleWrapper.getValue("exceptions","DuplicateSOPInstance", new Locale(DicomConfig.createInstance().getLocale())) + strSOPInstance);
						}
						return EnumImplOpsStatus.FAILURE_DUPLICATE.getValue();
					}

					if(objMediaCreation_DBAgent.createMediaCreationInstance(objDicomMessage.getDataSet(),strSOPInstance))
						return EnumImplOpsStatus.SUCCESS.getValue();
					else
						return EnumImplOpsStatus.FAILURE.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(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();
	}

	/**
	 * Checking whether provided sop instance has been created or not.
	 */
	private boolean isSOPInstanceExist(String strSOPInstance)throws SQLException
	{
		return objMediaCreation_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) 
	{
		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 = objDataSetList.get(0);

		DicomMessage objDicomMessage = new DicomMessage();
		objDicomMessage.setDataSet(objIDataSet);
		
		ICommandSet objICommandSet = new CommandSet();
		if(objQueryModel instanceof NCreateMediaCreationMang_QueryModel)
		{
			// set Command field
			ICommandElement objICommandElement = new CommandElement(0x0000,0x0100,EnumCommandField.N_CREATE_RQ.getValue()); 
			objICommandSet.addCommandElement(objICommandElement);

			// set Affected SOP Instance
			if(strValue == null)
				strValue = StandardMethods.generateUUID();
				
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger objDicomLogger = DicomLogger.getLogger();
				objDicomLogger.log(ResourceBundleWrapper.getValue("status","NCreate.InstanceCreated",new Locale(DicomConfig.createInstance().getLocale()))+ strValue);
			}
			
			ICommandElement objICEAffSOPInst = new CommandElement(0x0000,0x1000,strValue);
			objICommandSet.addCommandElement(objICEAffSOPInst);
		}

		objDicomMessage.setCommandSet(objICommandSet);

		return store(objDicomMessage, null);
	}
}
