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

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

import cdac.medinfo.sdk.dcm30_04.commoninterface.IDataSet;
import cdac.medinfo.sdk.dcm30_04.enums.EnumCommandField;
import cdac.medinfo.sdk.dcm30_04.exceptions.MandatoryMissingException;
import cdac.medinfo.sdk.dcm30_04.services.dicomnetcommons.EnumPriority;
import cdac.medinfo.sdk.dcm30_04.services.dicomnetcommons.ICommandElement;
import cdac.medinfo.sdk.dcm30_04.services.dicomnetcommons.InvalidCommandSetException;
import cdac.medinfo.sdk.dcm30_04.services.dicomnetcommons.InvalidDICOMMessageException;
import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.CommandElement;
import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.DIMSERequest;
import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.DicomMessage;
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 contains attributes of  C-Find request.
 * This request is created when CFind operation needs to be performed.
 * The C-FIND service is invoked by a DIMSE-service-user to match a series of Attribute strings
 * against the Attributes of the set of SOP Instances managed by a peer DIMSE-service-user.
 * The C-FIND service returns for each match a list of requested Attributes and their values.
 */
public class CFindRQ extends DIMSERequest 
{
	/**
	 * Instantiates a new C-Find-RQ.
	 */
	public CFindRQ()
	{
		
	}

	/**
	 * Instantiates a new C-Find-RQ.
	 * Sets the Dicom Message in C-Find request as provided by user.
	 * 
	 * @param objDicomMessge object of dicom message to be set in C-Find request.
	 * 
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	public CFindRQ(DicomMessage objDicomMessge) throws IOException
	{
		objICommandSet = objDicomMessge.getCommandSet();
		objIDataSet = objDicomMessge.getDataSet();
	}

	/**
	 * Sets Priority
	 * The priority shall be set to one of the following values:
	 * LOW = 0002H
	 * MEDIUM = 0000H
	 * HIGH = 0001H.
	 * 
	 * @param enumPriority enum value of Priority
	 */
	public void setPriority(EnumPriority enumPriority)
	{
		ICommandElement objICommandElement = null;
		objICommandElement = new CommandElement(0x0000, 0x0700,enumPriority.getValue());
		objICommandSet.addCommandElement(objICommandElement);
	}

	/**
	 * Retrieves Priority .
	 * 
	 * @return short - value of Priority.
	 */
	public short getPriority()
	{
		Object objValue = getValue(0x0000,0x0700);
		if(objValue != null)
			return Short.parseShort(objValue.toString());
		return DicomConstants.DCM_NO_VALUE;
	}
	
	/**
	 * Sets Affected SOP Class UID. . 
	 * SOP Class UID. associated with the operation.
	 * @param strAffectedSOPClassUID value of affected SOP Class UID..
	 */
	public void setAffectedSOPClassUID(String strAffectedSOPClassUID)
	{
		ICommandElement objICommandElement = null;
		objICommandElement = new CommandElement(0x0000, 0x0002,strAffectedSOPClassUID);
		objICommandSet.addCommandElement(objICommandElement);
	}

	/**
	 * Retrieves Affected SOP Class UID. . 
	 * SOP Class UID. associated with the operation.
	 * @return String - value of Affected SOP Class UID. .
	 */
	public String getAffectedSOPClassUID()
	{
		Object objValue = getValue(0x0000,0x0002);
		if(objValue != null)
			return objValue.toString();
		return null;
	}

	/**
	 * This method makes CFind RQ's according to the given DataSet Collection.
	 * 
	 * @param strAffectedSOPClassUID String value of Affected SOP Class UID.
	 * @param objIDataSetColl Collection of DataSet
	 * 
	 * @return ISingleCollection<CFindRQ> Collection of CFind RQ
	 */
	public static ISingleCollection<CFindRQ> getDefaultRQ(String strAffectedSOPClassUID,ISingleCollection<IDataSet> objIDataSetColl)
	{
		ICollectionIterator<IDataSet> objDataSetColIterator = objIDataSetColl.iterator();
		ISingleCollection<CFindRQ> objCollecCFindRQ = new SingleCollection<CFindRQ>();
		CFindRQ objCFind = null;
		short i = 0;
		while(objDataSetColIterator.hasNext())
		{
			IDataSet objIDataSet = objDataSetColIterator.next();
			objCFind= new CFindRQ();
			objCFind.setAffectedSOPClassUID(strAffectedSOPClassUID);
			objCFind.setCommandField(EnumCommandField.C_FIND_RQ);
			objCFind.setPriority(EnumPriority.HIGH);
			if(null != objIDataSet && !objIDataSet.isEmpty())
				objCFind.setCommandDataSetType(DicomConstants.DCM_DATASET_PRESENT);
			else
				objCFind.setCommandDataSetType(DicomConstants.DCM_DATASET_NOT_PRESENT);
			objCFind.setMessageID(i++);
			objCFind.setDataSet(objIDataSet);
			objCFind.setCommandGroupLength(objCFind.getCommandSet().getCommandSetLength());
			
			// Validating RQ.
			objCFind.validate();
			objCollecCFindRQ.add(objCFind);
		}
		return objCollecCFindRQ;
	}

	/**
	 * This method makes CFind RQ's according to the given DataSet Collection.
	 * 
	 * @param objIDataSet Data Set to be set in C-Find request.
	 * @param strAffectedSOPClassUID String value of Affected SOP Class UID.
	 * 
	 * @return ISingleCollection<CStoreRQ> Collection of CStore RQ
	 */
	public static CFindRQ getDefaultRQ(String strAffectedSOPClassUID,IDataSet objIDataSet)
	{
		CFindRQ objCFindRQ = new CFindRQ();
		objCFindRQ.setAffectedSOPClassUID(strAffectedSOPClassUID);
		objCFindRQ.setCommandField(EnumCommandField.C_FIND_RQ);
		objCFindRQ.setPriority(EnumPriority.HIGH);
		if(null != objIDataSet && !objIDataSet.isEmpty())
			objCFindRQ.setCommandDataSetType(DicomConstants.DCM_DATASET_PRESENT);
		else
			objCFindRQ.setCommandDataSetType(DicomConstants.DCM_DATASET_NOT_PRESENT);
		objCFindRQ.setMessageID(shMsgID++);
		objCFindRQ.setDataSet(objIDataSet);
		objCFindRQ.setCommandGroupLength(objCFindRQ.getCommandSet().getCommandSetLength());
		
		// Validating RQ.
		objCFindRQ.validate();
		return objCFindRQ;
	}
	
	/**
	 * Validates the request for their mandatory attributes only.
	 * @return true, if validation is successful.
	 * @throws InvalidDICOMMessageException If validation of mandatory fields fails.
	 */
	public boolean validate() throws InvalidDICOMMessageException
	{
		super.validate();
		try
		{		
			//Checks for service type.
			if(getCommandType() != EnumCommandField.C_FIND_RQ)
				throw new InvalidDICOMMessageException(ResourceBundleWrapper.getValue("exceptions","RQNotMatched",new Locale(DicomConfig.createInstance().getLocale())) + getCommandType().name());
			
			if(!objICommandSet.isPresent(0x0000,0x0002))			// Affected SOP Class UID.
				throw new MandatoryMissingException("0000,0002");
			else
			{
				if(objICommandSet.getValue(0x0000,0x0002) == null)
					throw new InvalidDICOMMessageException(ResourceBundleWrapper.getValue("exceptions", "NullValue",new Locale(DicomConfig.createInstance().getLocale())) + 0x0000 + "," + 0x0002);
			}
			
			if(!objICommandSet.isPresent(0x0000,0x0700))		// Priority
				throw new MandatoryMissingException("0000,0700");
			else
			{
				if(objICommandSet.getValue(0x0000,0x0700) == null)
					throw new InvalidDICOMMessageException(ResourceBundleWrapper.getValue("exceptions", "NullValue",new Locale(DicomConfig.createInstance().getLocale())) + 0x0000 + "," + 0x0700);
			}

			// For Identifier or Data Set
			if(objIDataSet == null || objIDataSet.isEmpty())
			{
				if(DicomConfig.createInstance().isLoggingOn())
					DicomLogger.getLogger().log(ResourceBundleWrapper.getValue("exceptions", "EmptyDataSet", new Locale(DicomConfig.createInstance().getLocale())));
				
				throw new InvalidDICOMMessageException(ResourceBundleWrapper.getValue("exceptions", "EmptyDataSet",new Locale(DicomConfig.createInstance().getLocale())));
			}
		}
		catch(MandatoryMissingException mme)
		{
			InvalidCommandSetException objCommandSetException = new InvalidCommandSetException(mme);
			if(DicomConfig.createInstance().isLoggingOn())
				DicomLogger.getLogger().log(mme.getMessage());

			throw new InvalidDICOMMessageException(this.getClass().getSimpleName(),objCommandSetException);
		}	
		return true;
	}
}
