/*******************************************************************************
 *  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.enums.EnumRTBeamLimitingDeviceType;
import cdac.medinfo.sdk.dcm30_04.exceptions.ConditionFailedException;
import cdac.medinfo.sdk.dcm30_04.exceptions.InvalidItemException;
import cdac.medinfo.sdk.dcm30_04.exceptions.InvalidMacroException;
import cdac.medinfo.sdk.dcm30_04.exceptions.MandatoryMissingException;
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 methods to validate, set and get attributes in Beam Limiting Device Sequence.
 */
public class BeamLimitingDeviceSequenceItem extends Item  
{
	

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

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

	/**
	 * This constructor creates the item and internal code sequence macro with specified TS.
	 * @param objTransferSyntax specifies the DICOM Standard defined TransfeSyntax 
	 */
	BeamLimitingDeviceSequenceItem(ITransferSyntax objITransferSyntax)
	{
		super(objITransferSyntax);
	}

	/**
	 * This constructor creates the item and internal code sequence macro with default TransferSyntax 
	 * and default DictionaryReader
	 * @param objTransferSyntax specifies the DICOM Standard defined TransfeSyntax
	 * @param objDictionaryReader specifies the DICOM Dictionary reader to be used 
	 */
	BeamLimitingDeviceSequenceItem(ITransferSyntax objTransferSyntax, IDictionaryReader objDictionaryReader)
	{
		super(objTransferSyntax,objDictionaryReader);
	}

	/**
	 * Validates all the attributes in {@link BeamLimitingDeviceSequenceItem} 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
		{
			super.validateForModule();
			// 300A,00B8 is a conditional element with mandatory like condition.
			if(!contains(0x300A,0x00B8))
				throw new MandatoryMissingException("300A,00B8") ;
			// 300A,00BC is a conditional element with mandatory like condition.
			if(!contains(0x300A,0x00BC))
				throw new MandatoryMissingException("300A,00BC");
			String strRTBeamLimitingDeviceType = getRTBeamLimitingDeviceType();
			if(((EnumRTBeamLimitingDeviceType.MULTILEAF_IEC_X_DIRECTION.getValue().equals(strRTBeamLimitingDeviceType)) || (EnumRTBeamLimitingDeviceType.MULTILEAF_IEC_Y_DIRECTION.getValue().equals(strRTBeamLimitingDeviceType))) && (!contains(0x300A,0x00BE)))
				throw new ConditionFailedException("Element 300A,00BE shall be present if value of Element 300A,00B8 is " + EnumRTBeamLimitingDeviceType.MULTILEAF_IEC_X_DIRECTION.getValue() + " or " + EnumRTBeamLimitingDeviceType.MULTILEAF_IEC_Y_DIRECTION.getValue());
		}
		catch( ConditionFailedException ce)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger.getLogger().log(ce.getMessage());
			}
			throw new InvalidItemException(this.getClass().getSimpleName(),ce);
		}
		catch( InvalidMacroException ime)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger.getLogger().log(ime.getMessage());
			}
			throw new InvalidItemException(this.getClass().getSimpleName(),ime);
		}
		return true;
	}

	/**
	 * Sets type of beam limiting device (collimator). Required if Beam Limiting Device Sequence (300A,00B6) is sent.
	 * Enumerated Values:
	 * 1) X = symmetric jaw pair in IEC X direction.
	 * 2) Y = symmetric jaw pair in IEC Y direction.
	 * 3) ASYMX = asymmetric jaw pair in IEC X direction.
	 * 4) ASYMY = asymmetric pair in IEC Y direction.
	 * 5) MLCX = multileaf (multi-element) jaw pair in IEC X direction.
	 * 6) MLCY = multileaf (multi-element) jaw pair in IEC Y direction.
	 * @param strRTBeamLimitingDeviceType - Specifies String value of RT Beam Limiting Device Type.
	 */
	public void setRTBeamLimitingDeviceType(String strRTBeamLimitingDeviceType)
	{
		/* Accept the RT Beam Limiting Device Type in String format of type CS.
		 * 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(0x300A, 0x00B8, strRTBeamLimitingDeviceType,getDictionaryReader());
		else
			objIDataElement = new ExplicitDE(0x300A, 0x00B8,DicomConstants.DCM_DT_CS, strRTBeamLimitingDeviceType);

		addDataElement(objIDataElement);
	}

	/**
	 * Retrieves type of beam limiting device (collimator).
	 * @return String - value of RT Beam Limiting Device Type.
	 */
	public String getRTBeamLimitingDeviceType()
	{
		Object objValue = getValue(0x300A, 0x00B8);
		if(objValue != null)
			return objValue.toString();
		return null;
	}

	/**
	 * Sets radiation source to beam limiting device (collimator) distance (mm).
	 * @param strSourceToBeamLimitingDeviceDistance -Specifies String value of Source to Beam Limiting Device Distance.
	 */
	public void setSourceToBeamLimitingDeviceDistance(String strSourceToBeamLimitingDeviceDistance)
	{
		/* Accept the Source to Beam Limiting Device Distance in String format of type CS.
		 * 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(0x300A, 0x00BA, strSourceToBeamLimitingDeviceDistance,getDictionaryReader());
		else
			objIDataElement = new ExplicitDE(0x300A, 0x00BA,DicomConstants.DCM_DT_DS, strSourceToBeamLimitingDeviceDistance);

		addDataElement(objIDataElement);
	}

	/**
	 * Retrieves type of beam limiting device (collimator).
	 * @return String - value of Source to Beam Limiting Device Distance.
	 */
	public String getSourceToBeamLimitingDeviceDistance()
	{
		Object objValue = getValue(0x300A, 0x00BA);
		if(objValue != null)
			return objValue.toString();
		return null;
	}

	/**
	 * Sets number of leaf (element) or jaw pairs (equal to 1 for standard beam limiting
	 * device jaws). Required if Beam Limiting Device Sequence (300A,00B6) is sent.
	 * @param strNumberOfLeafOrJawPairs -Specifies String value of Number of Leaf/Jaw Pairs.
	 */
	public void setNumberOfLeafOrJawPairs(String strNumberOfLeafOrJawPairs)
	{
		/* Accept the Number of Leaf/Jaw Pairs in String format of type IS.
		 * 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(0x300A, 0x00BC, strNumberOfLeafOrJawPairs,getDictionaryReader());
		else
			objIDataElement = new ExplicitDE(0x300A, 0x00BC,DicomConstants.DCM_DT_IS, strNumberOfLeafOrJawPairs);

		addDataElement(objIDataElement);
	}

	/**
	 * Retrieves number of leaf (element) or jaw pairs (equal to 1 for standard beam limiting
	 * device jaws).
	 * @return String - Specifies String value of  Specifies String value of Number of Leaf/Jaw Pairs.
	 */
	public String getNumberOfLeafOrJawPairs()
	{
		Object objValue = getValue(0x300A, 0x00BC);
		if(objValue != null)
			return objValue.toString();
		return null;
	}

	/**
	 * Sets positions of diaphragm jaw pairs (in mm) in IEC BEAM LIMITING DEVICE coordinate
	 * axis in the IEC order X1, X2, Y1, Y2.
	 * @param arrStrLeafPositionBoundaries -String array of  Leaf Position Boundaries.
	 */	
	public void setLeafPositionBoundaries(String[] arrStrLeafPositionBoundaries)
	{
		/* Accept the Leaf Position Boundaries value in String Array format of type DS.
		 * Read the Transfer Syntax and check to create ImplicitDE or ExplicitDE .
		 * Set the iGroupNumber and iElementNumber to ImplicitDE object 
		 * Set the iVRType
		 * Set length from the element
		 * Add this element to the Hash Map
		 */
		IDataElement objIDataElement = null;
		if(objITransferSyntax.getVRTransferSyntax() == DicomConstants.DCM_VR_IMPLICIT)
			objIDataElement = new ImplicitDE(0x300A, 0x00BE,arrStrLeafPositionBoundaries,objIDictionaryReader);
		else
			objIDataElement = new ExplicitDE(0x300A, 0x00BE, DicomConstants.DCM_DT_DS,arrStrLeafPositionBoundaries);
		if(objIDataElement != null)
			addDataElement(objIDataElement);
	}

	/**
	 * Retrieves positions of diaphragm jaw pairs (in mm) in IEC BEAM LIMITING DEVICE coordinate
	 * axis in the IEC order X1, X2, Y1, Y2.
	 * @return arrStrOperatorNames - String value of  Leaf Position Boundaries.
	 */
	public String[] getLeafPositionBoundaries()
	{
		Object objValue = getValue(0x300A, 0x00BE);
		if(objValue != null)
			return (String[])objValue;
		return null;
	}

	/**
	 * Sets positions of beam limiting device (collimator) leaf or jaw (element) pairs (in
	 * mm) in IEC BEAM LIMITING DEVICE coordinate axis appropriate to RT Beam Limiting Device Type (300A,00B8).
	 * @param arrStrLeafOrJawPositions- String value of  Leaf/Jaw Positions.
	 */	
	public void setLeafOrJawPositions(String[] arrStrLeafOrJawPositions)
	{
		/* Accept the Leaf/Jaw Positions value in String Array format of type DS.
		 * Read the Transfer Syntax and check to create ImplicitDE or ExplicitDE .
		 * Set the iGroupNumber and iElementNumber to ImplicitDE object 
		 * Set the iVRType
		 * Set length from the element
		 * Add this element to the Hash Map
		 */
		IDataElement objIDataElement = null;
		if(objITransferSyntax.getVRTransferSyntax() == DicomConstants.DCM_VR_IMPLICIT)
			objIDataElement = new ImplicitDE(0x300A, 0x011C,arrStrLeafOrJawPositions,objIDictionaryReader);
		else
			objIDataElement = new ExplicitDE(0x300A, 0x011C, DicomConstants.DCM_DT_DS,arrStrLeafOrJawPositions);
		if(objIDataElement != null)
			addDataElement(objIDataElement);
	}

	/**
	 * Retrieves positions of beam limiting device (collimator) leaf or jaw (element) pairs (in
	 * mm) in IEC BEAM LIMITING DEVICE coordinate axis appropriate to RT Beam Limiting Device Type (300A,00B8).
	 * @return arrStrOperatorNames - String value of  Leaf/Jaw Positions.
	 */
	public String[] getLeafOrJawPositions()
	{
		Object objValue = getValue(0x300A, 0x011C);
		if(objValue != null)
			return (String[])objValue;
		return null;
	}

	/**
	 * Retrieves pre-initialized object of Applicator 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 ApplicatorSequence - instance of Applicator Sequence. 
	 */
	public ApplicatorSequence getApplicatorSequence()
	{
		ApplicatorSequence objApplicatorSequence = null;
		IDataElement objIDataElement =  getDataForTag(0x300A,0x0107);
		if(objIDataElement != null)
		{
			IDicomValue objIDicomValue = objIDataElement.getDicomValue();
			if(objIDicomValue != null)
				objApplicatorSequence = (ApplicatorSequence)objIDicomValue;
		}
		else
		{
			DicomV3Factory objDicomV3Factory = DicomV3Factory.createInstance();
			int iVRTransferSyntax = objITransferSyntax.getVRTransferSyntax();
			objIDataElement = null;
			objApplicatorSequence = (ApplicatorSequence)objDicomV3Factory.createSequence(0x300A,0x0107, objITransferSyntax, objIDictionaryReader);

			if(iVRTransferSyntax == DicomConstants.DCM_VR_IMPLICIT)
				objIDataElement = new ImplicitDE(0x300A,0x0107, objApplicatorSequence.getValue(),objIDictionaryReader);
			else
				objIDataElement = new ExplicitDE(0x300A,0x0107, DicomConstants.DCM_DT_SQ, objApplicatorSequence.getValue());
			objIDataElement.setTransferSyntax(objITransferSyntax);
			if(objIDataElement != null)
				addDataElement(objIDataElement);
		}
		return objApplicatorSequence;
	}

	/**
	 * Retrieves pre-initialized object of Block 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 BlockSequence - instance of Block Sequence. 
	 */
	public BlockSequence getBlockSequence()
	{
		BlockSequence objBlockSequence = null;
		IDataElement objIDataElement =  getDataForTag(0x300A,0x00F4);
		if(objIDataElement != null)
		{
			IDicomValue objIDicomValue = objIDataElement.getDicomValue();
			if(objIDicomValue != null)
				objBlockSequence = (BlockSequence)objIDicomValue;
		}
		else
		{
			DicomV3Factory objDicomV3Factory = DicomV3Factory.createInstance();
			int iVRTransferSyntax = objITransferSyntax.getVRTransferSyntax();
			objIDataElement = null;
			objBlockSequence = (BlockSequence)objDicomV3Factory.createSequence(0x300A,0x00F4, objITransferSyntax, objIDictionaryReader);

			if(iVRTransferSyntax == DicomConstants.DCM_VR_IMPLICIT)
				objIDataElement = new ImplicitDE(0x300A,0x00F4, objBlockSequence.getValue(),objIDictionaryReader);
			else
				objIDataElement = new ExplicitDE(0x300A,0x00F4, DicomConstants.DCM_DT_SQ, objBlockSequence.getValue());
			objIDataElement.setTransferSyntax(objITransferSyntax);
			if(objIDataElement != null)
				addDataElement(objIDataElement);
		}
		return objBlockSequence;
	}
}
