/*******************************************************************************
 *  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.IDataSet;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IDictionaryReader;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IItem;
import cdac.medinfo.sdk.dcm30_04.enums.EnumTemporalRangeType;
import cdac.medinfo.sdk.dcm30_04.exceptions.ConditionFailedException;
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;




/**
 * Temporal Coordinates Macro specifies the Attributes that convey TCOORD Content Items.
 * A TCOORD Content Item shall be the Source Content Item of one or more SELECTED FROM relationships with one
 * or more SCOORD Content Items, one or more IMAGE Content Items, or one or more WAVEFORM Content Items.
 */
public class TemporalCoordinatesMacro extends Macro  
{
	

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

	/**
	 * This constructor constructs a Macro with specified DataSet.
	 * @param objDataSet Collection of Data Elements 
	 */
	public TemporalCoordinatesMacro(IDataSet objDataSet)
	{
		super(objDataSet);
	}

	/**
	 * This constructor constructs a Macro with specified DataSet and DictionaryReader
	 * @param objDataSet specifies the DataSet
	 * @param objDictionaryReader specifies the DICOM Dictionary reader to be used 
	 */
	public TemporalCoordinatesMacro(IDataSet objDataSet,IDictionaryReader objDictionaryReader)
	{
		super(objDataSet,objDictionaryReader);
	}

	/**
	 * This constructor constructs a Macro with the specified Item
	 * @param objItem specifies instance of Item class
	 */
	public TemporalCoordinatesMacro(IItem objItem)
	{
		super(objItem);
	}

	/**
	 * This constructor constructs a Macro with the specified Item and DictionaryReader
	 * @param objItem specifies instance of Item class
	 * @param objDictionaryReader specifies the DICOM Dictionary reader to be used 
	 */
	public TemporalCoordinatesMacro(IItem objItem,IDictionaryReader objDictionaryReader)
	{
		super(objItem, objDictionaryReader);
	}

	/**
	 * This Attribute defines the type of temporal extent of the region of interest
	 * @param enumTemporalRangeType  String value of Temporal Range Type
	 */
	public void setTemporalRangeType(EnumTemporalRangeType enumTemporalRangeType)
	{
		/* Accept the Temporal Range Type 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(0x0040,0xA130, enumTemporalRangeType.getValue(),objIDictionaryReader);
		else
			objIDataElement = new ExplicitDE(0x0040,0xA130,DicomConstants.DCM_DT_CS, enumTemporalRangeType.getValue());

		addDataElement(objIDataElement);

	}

	/**
	 * Return the type of temporal extent of the region of interest
	 * @return String - value of Temporal Range Type
	 */
	public String getTemporalRangeType()
	{
		Object objValue = getValue(0x0040,0xA130);
		if(objValue != null)
			return objValue.toString();
		return null;
	}

	/**
	 * Sets List of samples within a multiplex group specifying temporal points of the referenced data.
	 * Position of first sample is 1.
	 * @param lArrReferencedSamplePositions  int array of Referenced Sample Positions
	 */
	public void setReferencedSamplePositions(int[] lArrReferencedSamplePositions)
	{
		/* Accept the Referenced Sample Positions of type UL.
		 * 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,0xA132, lArrReferencedSamplePositions,objIDictionaryReader);
		else
			objIDataElement = new ExplicitDE(0x0040,0xA132,DicomConstants.DCM_DT_UL, lArrReferencedSamplePositions);

		addDataElement(objIDataElement);

	}

	/**
	 * Return Referenced Sample Positions
	 * @return long[] - long array of Referenced Sample Positions
	 */
	public int[] getReferencedSamplePositions()
	{
		Object objValue = getValue(0x0040,0xA132);
		if(objValue != null)
			return (int[])objValue;
		return null;
	}

	/**
	 * Sets temporal points for reference by number of seconds after start of data.
	 * @param arrStrReferencedTimeOffsets  String array of Referenced Time Offsets
	 */
	public void setReferencedTimeOffsets(String[] arrStrReferencedTimeOffsets)
	{
		/* Accept the Referenced Time Offsets of type DS.
		 * 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,0xA138, arrStrReferencedTimeOffsets,objIDictionaryReader);
		else
			objIDataElement = new ExplicitDE(0x0040,0xA138,DicomConstants.DCM_DT_DS, arrStrReferencedTimeOffsets);

		addDataElement(objIDataElement);

	}

	/**
	 * Return temporal points for reference by number of seconds after start of data.
	 * @return String - array of Referenced Time Offsets
	 */
	public String[] getReferencedTimeOffsets()
	{
		Object objValue = getValue(0x0040,0xA138);
		if(objValue != null)
			return (String[])objValue;
		return null;
	}

	/**
	 * Sets temporal points for reference by absolute time.
	 * @param arrStrReferencedDatetime  String array of Referenced Date time
	 */
	public void setReferencedDatetime(String[] arrStrReferencedDatetime)
	{
		/* Accept the Referenced Datetime of type DT.
		 * 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,0xA13A, arrStrReferencedDatetime,objIDictionaryReader);
		else
			objIDataElement = new ExplicitDE(0x0040,0xA13A,DicomConstants.DCM_DT_DT, arrStrReferencedDatetime);

		addDataElement(objIDataElement);

	}

	/**
	 * Return temporal points for reference by absolute time.
	 * @return String - value of Referenced Date time
	 */
	public String[] getReferencedDatetime()
	{
		Object objValue = getValue(0x0040,0xA13A);
		if(objValue != null)
			return (String[])objValue;
		return null;
	}

	/**
	 * Validates all the attributes in Temporal Coordinates Macro
	 * @return boolean - Success -true, Failure -false.
	 * @throws InvalidMacroException throws InvalidMacroException If Mandatory or Conditional element fails.
	 */
	public boolean validate() throws InvalidMacroException
	{
		if(iMacroLevel == DicomConstants.DCM_MODULE_LEVEL_MACRO)
			return validate(objIDataSet);
		else if(iMacroLevel == DicomConstants.DCM_ITEM_LEVEL_MACRO)
			return validate(objIItem);
		return false;
	}

	/**
	 * Validates all the attributes in Temporal Coordinates Macro that are present in the DataSet
	 * @param objIDataSet collection of DataElements
	 * @return boolean - Success -true, Failure - false
	 * @throws InvalidMacroException throws InvalidMacroException If Mandatory or Conditional element fails.
	 */
	public static boolean validate(IDataSet objIDataSet) throws InvalidMacroException
	{
		try
		{
			/*
			 * Validation Rules for Mandatory Elements
			 */
			if(!objIDataSet.isPresent(0x0040,0xA130))
				throw new MandatoryMissingException("0040,A130");
			if(!(objIDataSet.isPresent(0x0040,0xA132) && objIDataSet.isPresent(0x0040,0xA13A)) && !objIDataSet.isPresent(0x0040,0xA138))
				throw new ConditionFailedException("0040,A138 Required if Referenced Sample Positions (0040,A132) and Referenced Datetime (0040,A13A) are not present");
			if(!(objIDataSet.isPresent(0x0040,0xA132) && objIDataSet.isPresent(0x0040,0xA138)) && !objIDataSet.isPresent(0x0040,0xA13A))
				throw new ConditionFailedException("0040,A13A Required if Referenced Sample Positions (0040,A132) and Referenced Datetime (0040,A138) are not present");
			/*
			 * 0040,A132 Referenced Sample Positions
			 * Required if the Referenced SOP Instance is a Waveform and Referenced Time Offsets (0040,A138) and Referenced Datetime
			 * (0040,A13A) are not present.
			 */
			if(!(objIDataSet.isPresent(0x0040,0xA138) && objIDataSet.isPresent(0x0040,0xA13A)) && !objIDataSet.isPresent(0x0040,0xA132))
				throw new ConditionFailedException("0040,A132 Required if Referenced Time Offsets (0040,A138) and Referenced Datetime (0040,A13A) are not present.");
		}
		catch( MandatoryMissingException me)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger.getLogger().log(me.getMessage());
			}
			throw new InvalidMacroException(TemporalCoordinatesMacro.class.getSimpleName(),me);
		}
		catch( ConditionFailedException cfe)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger.getLogger().log(cfe.getMessage());
			}
			throw new InvalidMacroException(TemporalCoordinatesMacro.class.getSimpleName(),cfe);
		}
		return true;
	}

	/**
	 * Validates all the attributes in Temporal Coordinates Macro that are present in the DataSet
	 * @param objIItem collection of DataElements in a sequence
	 * @return boolean Success -true, Failure - false
	 * @throws InvalidMacroException throws InvalidMacroException If Mandatory or Conditional element fails.
	 */
	public static boolean validate(IItem objIItem) throws InvalidMacroException
	{
		try
		{
			/*
			 * Validation Rule for Mandatory Elements
			 */
			if(!objIItem.contains(0x0040,0xA130))
				throw new MandatoryMissingException("0040,A130");
			if(!(objIItem.contains(0x0040,0xA132) && objIItem.contains(0x0040,0xA13A)) && !objIItem.contains(0x0040,0xA138))
				throw new ConditionFailedException("0040,A138 Required if Referenced Sample Positions (0040,A132) and Referenced Datetime (0040,A13A) are not present");
			if(!(objIItem.contains(0x0040,0xA132) && objIItem.contains(0x0040,0xA138)) && !objIItem.contains(0x0040,0xA13A))
				throw new ConditionFailedException("0040,A13A Required if Referenced Sample Positions (0040,A132) and Referenced Datetime (0040,A138) are not present");
			/*
			 * 0040,A132 Referenced Sample Positions
			 * Required if the Referenced SOP Instance is a Waveform and Referenced Time Offsets (0040,A138) and Referenced Datetime
			 * (0040,A13A) are not present.
			 */
			if(!(objIItem.contains(0x0040,0xA138) && objIItem.contains(0x0040,0xA13A)) && !objIItem.contains(0x0040,0xA132))
				throw new ConditionFailedException("0040,A132 Required if Referenced Time Offsets (0040,A138) and Referenced Datetime (0040,A13A) are not present.");
		}
		catch( MandatoryMissingException me)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger.getLogger().log(me.getMessage());
			}
			throw new InvalidMacroException("Temporal Coordinates Macro",me);
		}
		catch( ConditionFailedException cfe)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger.getLogger().log(cfe.getMessage());
			}
			throw new InvalidMacroException("Temporal Coordinates Macro",cfe);
		}
		return true;
	}
}
