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

import cdac.medinfo.sdk.dcm30_04.commoninterface.IDataElement;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IDicomValue;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IDictionaryReader;
import cdac.medinfo.sdk.dcm30_04.commoninterface.ITransferSyntax;
import cdac.medinfo.sdk.dcm30_04.exceptions.InvalidItemException;
import cdac.medinfo.sdk.dcm30_04.exceptions.MandatoryMissingException;
import cdac.medinfo.sdk.dcm30_04.exceptions.ValidationException;
import cdac.medinfo.sdk.dcm30_04.utils.DicomConfig;
import cdac.medinfo.sdk.dcm30_04.utils.DicomConstants;
import cdac.medinfo.sdk.dcm30_04.utils.DicomLogger;


/**
* This item class contains the methods to set, get and validate the attribute present in Real World Value Mapping Sequence.
 */
public class RealWorldValueMappingSequenceItem extends Item
{
	

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * This constructor creates the item and internal code sequence macro with default TransferSyntax 
	 */
	RealWorldValueMappingSequenceItem()
	{
		super();
	}

	/**
	 * This constructor creates the item and internal code sequence macro with default TransferSyntax 
	 * and default DictionaryReader
	 * @param objITransferSyntax specifies the DICOM Standard defined TransfeSyntax
	 */
	RealWorldValueMappingSequenceItem(ITransferSyntax objITransferSyntax)
	{
		super(objITransferSyntax);
	}

	/**
	 * This constructor creates Recorded Source Applicator Sequence Item with specified TransferSyntax and
	 * specified DictionaryReader
	 * @param objTransferSyntax specifies the DICOM Standard defined TransfeSyntax
	 * @param objDictionaryReader specifies the DICOM Dictionary reader to be used 
	 */
	RealWorldValueMappingSequenceItem(ITransferSyntax objTransferSyntax, IDictionaryReader objDictionaryReader)
	{
		super(objTransferSyntax,objDictionaryReader);
	}
	
	/**
	 * Sets Specifies the first stored value mapped for the Real Word Value Intercept (0040,9224) and Real World Value Slope
	 *(0040,9225) or Real World Value LUT (0040,9212) of this Item.
	 * @param shRealWorldValueFirstValueMapped short value of RealWorldValueFirstValueMapped
	 */
	public void setRealWorldValueFirstValueMapped(short shRealWorldValueFirstValueMapped)
	{
		/* Accept the Failure Reason in of type US.
		 * Read the Transfer Syntax and check if ImplicitDE or ExplicitDE to create
		 * Set the iGroupNumber and iElementNumber to ImplicitDE object 
		 * Set the iVRType
		 * Set length from the element
		 * Add this element to the Data Set
		 */
		IDataElement objIDataElement = null;
		if(objITransferSyntax.getVRTransferSyntax() == DicomConstants.DCM_VR_IMPLICIT)	
			objIDataElement = new ImplicitDE(0x0040,0x9216, shRealWorldValueFirstValueMapped,getDictionaryReader());
		else
			objIDataElement = new ExplicitDE(0x0040,0x9216,DicomConstants.DCM_DT_US, shRealWorldValueFirstValueMapped);

		addDataElement(objIDataElement);
	}

	/**
	 * Retrieves The reason that storage commitment could not be provided for this SOP Instance.
	 * @return short - value of Failure Reason.
	 */
	public short getRealWorldValueFirstValueMapped()
	{
		Object objValue = getValue(0x0040,0x9216);
		if(objValue != null)
			return Short.parseShort(objValue.toString());
		return DicomConstants.DCM_NO_VALUE;
	}
	
	/**
	 * Specifies the last stored value mapped for the Real Word Value Intercept (0040,9224) and Real World Value Slope
	 * (0040,9225) or Real World Value LUT (0040,9212) of this Item.
	 * @param shRealWorldValueLastValueMapped short value of RealWorldValueLastValueMapped
	 */
	public void setRealWorldValueLastValueMapped(short shRealWorldValueLastValueMapped)
	{
		/* Accept the Failure Reason in of type US.
		 * Read the Transfer Syntax and check if ImplicitDE or ExplicitDE to create
		 * Set the iGroupNumber and iElementNumber to ImplicitDE object 
		 * Set the iVRType
		 * Set length from the element
		 * Add this element to the Data Set
		 */
		IDataElement objIDataElement = null;
		if(objITransferSyntax.getVRTransferSyntax() == DicomConstants.DCM_VR_IMPLICIT)	
			objIDataElement = new ImplicitDE(0x0040,0x9211, shRealWorldValueLastValueMapped,getDictionaryReader());
		else
			objIDataElement = new ExplicitDE(0x0040,0x9211,DicomConstants.DCM_DT_US, shRealWorldValueLastValueMapped);

		addDataElement(objIDataElement);
	}

	/**
	 * Retrieves The reason that storage commitment could not be provided for this SOP Instance.
	 * @return Short - value of Failure Reason.
	 */
	public short getRealWorldValueLastValueMapped()
	{
		Object objValue = getValue(0x0040,0x9211);
		if(objValue != null)
			return Short.parseShort(objValue.toString());
		return DicomConstants.DCM_NO_VALUE;
	}
	
	/**
	 * The Intercept value in relationship between stored values (SV) and the real world values.
	 * @param dRealWorldValueIntercept 
	 */
	public void setRealWorldValueIntercept(double dRealWorldValueIntercept)
	{
		/*Accept the RealWorldValueIntercept in Double format of type FD
		 * Read the Transfer Syntax and check if ImplicitDE or ExplicitDE to create
		 * 
		 * Set the iGroupNumber and iElementNumber to ImplicitDE object 
		 * Set the iVRType
		 * Set length from the element
		 * Add this element to the Data Set
		 */
		IDataElement objIDataElement = null;
		if(objITransferSyntax.getVRTransferSyntax() == DicomConstants.DCM_VR_IMPLICIT)
			objIDataElement = new ImplicitDE(0x0040,0x9224, dRealWorldValueIntercept,getDictionaryReader());
		else
			objIDataElement = new ExplicitDE(0x0040,0x9224,DicomConstants.DCM_DT_FD, dRealWorldValueIntercept);

		addDataElement(objIDataElement);


	}

	/**
	 * Return RealWorldValueIntercept.
	 * @return double - double value of value increments per positive X pixel increment.
	 */
	public double getRealWorldValueIntercept()
	{
		Object objValue = getValue(0x0040,0x9224);
		if(objValue != null)
			return Double.parseDouble(objValue.toString());
		return DicomConstants.DCM_NO_VALUE;
	}
	
	/**
	 * sets RealWorldValueScope
	 * @param dRealWorldValueScope The Slope value in relationship between stored values (SV) and the real world values.
	 */
	public void setRealWorldValueScope(double dRealWorldValueScope)
	{
		/*Accept the RealWorldValueScope in Double format of type FD
		 * Read the Transfer Syntax and check if ImplicitDE or ExplicitDE to create
		 * 
		 * Set the iGroupNumber and iElementNumber to ImplicitDE object 
		 * Set the iVRType
		 * Set length from the element
		 * Add this element to the Data Set
		 */
		IDataElement objIDataElement = null;
		if(objITransferSyntax.getVRTransferSyntax() == DicomConstants.DCM_VR_IMPLICIT)
			objIDataElement = new ImplicitDE(0x0040,0x9225, dRealWorldValueScope,getDictionaryReader());
		else
			objIDataElement = new ExplicitDE(0x0040,0x9225,DicomConstants.DCM_DT_FD, dRealWorldValueScope);

		addDataElement(objIDataElement);


	}

	/**
	 * Return RealWorldValueScope.
	 * @return double - double value of RealWorldValueScope.
	 */
	public double getRealWorldValueScope()
	{
		Object objValue = getValue(0x0040,0x9225);
		if(objValue != null)
			return Double.parseDouble(objValue.toString());
		return DicomConstants.DCM_NO_VALUE;
	}
	
	/**
	 * Sets LUT Data in this Sequence.Required if Real World Value Intercept(0040,9224) is not present.
	 * @param arrdblRealWorldValueLUTData array of double values for Real World Value LUT Data
	 */
	public void setRealWorldValueLUTData(double[] arrdblRealWorldValueLUTData)
	{
		/*Accept the Value Type in double format of type FD.
		 * Read the Transfer Syntax and check if ImplicitDE or ExplicitDE to create
		 * Set the iGroupNumber and iElementNumber to ImplicitDE object 
		 * Set the iVRType
		 * Set length from the element
		 * Add this element to the Data Set
		 */
		IDataElement objIDataElement = null;
		if(objITransferSyntax.getVRTransferSyntax() == DicomConstants.DCM_VR_IMPLICIT)
			objIDataElement = new ImplicitDE(0x0040,0x9212, arrdblRealWorldValueLUTData,getDictionaryReader());
		else
			objIDataElement = new ExplicitDE(0x0040,0x9212,DicomConstants.DCM_DT_FD, arrdblRealWorldValueLUTData);

		addDataElement(objIDataElement);

	}

	/**
	 * Retrieves cosines of a normal vector perpendicular to the selection plane with respect to the patient.
	 * @return double[] - double values of cosines in normal vector
	 */
	public double[] getRealWorldValueLUTData()
	{
		Object objValue = getValue(0x0040,0x9212);
		if(objValue != null)
			return (double[])objValue;
		return null;
	}
	
	/**
	 * Sets Free form text explanation of the meaning of the LUT.
	 * @param strLUTExplanation String value of LUT Explanation.
	 */
	public void setLUTExplanation(String strLUTExplanation)
	{
		/*Accept the LUT Explanation in String format of type LO.
		 * Read the Transfer Syntax and check if ImplicitDE or ExplicitDE to create
		 * 
		 * Set the iGroupNumber and iElementNumber to ImplicitDE object 
		 * Set the iVRType
		 * Set length from the element
		 * Add this element to the Data Set
		 */
		IDataElement objIDataElement = null;
		if(objITransferSyntax.getVRTransferSyntax() == DicomConstants.DCM_VR_IMPLICIT)
			objIDataElement = new ImplicitDE(0x0028, 0x3003, strLUTExplanation,objIDictionaryReader);
		else
			objIDataElement = new ExplicitDE(0x0028, 0x3003,DicomConstants.DCM_DT_LO, strLUTExplanation);
		//Add the DataElement to the Item
		addDataElement(objIDataElement);
	}

	/**
	 * Retrieves Free form text explanation of the meaning of the LUT
	 * @return String - value of LUT Explanation.
	 */
	public String getLUTExplanation()
	{
		Object objValue = getValue(0x0028, 0x3003);
		if(objValue != null)
			return objValue.toString();
		return null;
	}
	
	/**
	 * Sets Label that is used to identify this transformation.
	 * @param strLUTLabel short value of LUT Label.
	 */
	public void setLUTLabel(short strLUTLabel)
	{
		/*Accept the LUT Explanation in short format of type SH.
		 * Read the Transfer Syntax and check if ImplicitDE or ExplicitDE to create
		 * 
		 * Set the iGroupNumber and iElementNumber to ImplicitDE object 
		 * Set the iVRType
		 * Set length from the element
		 * Add this element to the Data Set
		 */
		IDataElement objIDataElement = null;
		if(objITransferSyntax.getVRTransferSyntax() == DicomConstants.DCM_VR_IMPLICIT)
			objIDataElement = new ImplicitDE(0x0040,0x9210, strLUTLabel,objIDictionaryReader);
		else
			objIDataElement = new ExplicitDE(0x0040,0x9210,DicomConstants.DCM_DT_SH, strLUTLabel);
		//Add the DataElement to the Item
		addDataElement(objIDataElement);
	}

	/**
	 * Retrieves LUTLabel
	 * @return short - value of LUT Label.
	 */
	public short getLUTLabel()
	{
		Object objValue = getValue(0x0040,0x9210);
		if(objValue != null)
			return Short.parseShort(objValue.toString());
		return DicomConstants.DCM_NO_VALUE;
	}
	
	/**
	 * Retrieves pre-initialized object of Measurement Units Code Sequence.If the module contains the sequence object
	 * it returns the same otherwise it creates the sequence adds to the module with proper initialization
	 * and then returns the object of sequence.
	 * @return MeasurementUnitsCodeSequence - instance of MeasurementUnitsCodeSequence. 
	 */
	public MeasurementUnitsCodeSequence getMeasurementUnitsCodeSequence()
	{
		MeasurementUnitsCodeSequence objMeasurementUnitsCodeSequence = null;
		IDataElement objIDataElement =  getDataForTag(0x0040,0x08EA);
		if(objIDataElement != null)
		{
			IDicomValue objIDicomValue = objIDataElement.getDicomValue();
			if(objIDicomValue != null)
				objMeasurementUnitsCodeSequence = (MeasurementUnitsCodeSequence)objIDicomValue;
		}
		else
		{
			DicomV3Factory objDicomV3Factory = DicomV3Factory.createInstance();
			int iVRTransferSyntax = objITransferSyntax.getVRTransferSyntax();
			objIDataElement = null;
			objMeasurementUnitsCodeSequence = (MeasurementUnitsCodeSequence)objDicomV3Factory.createSequence(0x0040,0x08EA, objITransferSyntax, objIDictionaryReader);

			if(iVRTransferSyntax == DicomConstants.DCM_VR_IMPLICIT)
				objIDataElement = new ImplicitDE(0x0040,0x08EA, objMeasurementUnitsCodeSequence.getValue(),objIDictionaryReader);
			else
				objIDataElement = new ExplicitDE(0x0040,0x08EA, DicomConstants.DCM_DT_SQ, objMeasurementUnitsCodeSequence.getValue());
			objIDataElement.setTransferSyntax(objITransferSyntax);
			if(objIDataElement != null)
				addDataElement(objIDataElement);
		}
		return objMeasurementUnitsCodeSequence;
	}
	
	/**
	 * Validates all the attributes in {@link RealWorldValueMappingSequenceItem} that are present in the DataSet.
	 * @return boolean - Success -true, Failure - false.
	 * @throws InvalidItemException throws InvalidItemException If Mandatory or Conditional element fails.
	 */
	public boolean validateForModule()  throws InvalidItemException
	{
		try
		{
			if(!contains(0x0040,0x9216))
				throw new MandatoryMissingException("0040,9216");
			if(!contains(0x0040,0x9211))
				throw new MandatoryMissingException("0040,9211");
			if(!contains(0x0040,0x9212) && !contains(0x0040,0x9224))
				throw new MandatoryMissingException("0040,9224");
			if(!contains(0x0040,0x9212) && !contains(0x0040,0x9225))
				throw new MandatoryMissingException("0040,9225");
			if(!contains(0x0040,0x9224) && !contains(0x0040,0x9212))
				throw new MandatoryMissingException("0040,9212");
			if(!contains(0x0028,0x3003))
				throw new MandatoryMissingException("0028,3003");
			if(!contains(0x0040,0x9210))
				throw new MandatoryMissingException("0040,9210");
			if(!contains(0x0040,0x08EA))
				throw new MandatoryMissingException("0040,08EA");
			else
				getMeasurementUnitsCodeSequence().validate();
		}
		catch(MandatoryMissingException me)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger.getLogger().log(me.getMessage());
			}
			throw new ValidationException(this.getClass().getSimpleName(),me);
		}
		return true;
	}
}
