/*******************************************************************************
 *  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.IDicomValue;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IDictionaryReader;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IItem;
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 macro specifies the Attributes that convey a reference to a DICOM image.
 */
public class ImageReferenceMacro extends Macro  
{
	

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	CompositeObjectReferenceMacro objCompositeObjectReferenceMacro = null;

	/**
	 * This constructor constructs a Macro with specified DataSet.
	 * @param objDataSet Collection of DataElements 
	 */
	public ImageReferenceMacro(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 ImageReferenceMacro(IDataSet objDataSet,IDictionaryReader objDictionaryReader)
	{
		super(objDataSet,objDictionaryReader);
	}

	/**
	 * This constructor constructs a Macro with the specified Item
	 * @param objItem specifies instance of Item class
	 */
	public ImageReferenceMacro(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 ImageReferenceMacro(IItem objItem,IDictionaryReader objDictionaryReader)
	{
		super(objItem, objDictionaryReader);
	}

	/**
	 * Retrieves the instance of Composite Object Reference Macro. If the instance is not already present a new instance 
	 * is created and returned. It is used to set the attribtues of Composite Object Reference Macro.
	 * @return - instance of CompositeObjectReferenceMacro.
	 */
	public CompositeObjectReferenceMacro getCompositeObjectReferenceMacro()
	{
		if(objCompositeObjectReferenceMacro == null)
		{
			if(iMacroLevel == DicomConstants.DCM_MODULE_LEVEL_MACRO)
				objCompositeObjectReferenceMacro = new CompositeObjectReferenceMacro(objIDataSet);
			else 
				objCompositeObjectReferenceMacro = new CompositeObjectReferenceMacro(objIItem);

			return objCompositeObjectReferenceMacro;
		}
		return objCompositeObjectReferenceMacro;
	}

	/**
	 * Identifies the frame numbers within the Referenced SOP Instance to which the reference applies.
	 * The first frame shall be denoted as frame number 1.
	 * @param arrStrReferencedFrameNumber String array of Referenced Frame Number
	 */
	public void setReferencedFrameNumber(String[] arrStrReferencedFrameNumber)
	{
		/* Accept the Referenced Frame Number 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(0x0008,0x1160, arrStrReferencedFrameNumber,objIDictionaryReader);
		else
			objIDataElement = new ExplicitDE(0x0008,0x1160,DicomConstants.DCM_DT_IS, arrStrReferencedFrameNumber);

		addDataElement(objIDataElement);
	}

	/**
	 * Return array of Referenced Frame Number
	 * @return String - array of Referenced Frame Number
	 */
	public String[] getReferencedFrameNumber()
	{
		Object objValue = getValue(0x0008,0x1160);
		if(objValue != null)
			return (String[])objValue;
		return null;
	}

	/**
	 * Retrieves pre-initialized object of Referenced SOP 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 ReferencedSOPSequence - instance of Referenced SOP Sequence. 
	 */
	public ReferencedSOPSequence getReferencedSOPSequence()
	{
		ReferencedSOPSequence objReferencedSOPSequence = null;
		IDataElement objIDataElement =  getDataElement(0x0008,0x1199);
		if(objIDataElement != null)
		{
			IDicomValue objIDicomValue = objIDataElement.getDicomValue();
			if(objIDicomValue != null)
				objReferencedSOPSequence = (ReferencedSOPSequence)objIDicomValue;
		}
		else
		{
			DicomV3Factory objDicomV3Factory = DicomV3Factory.createInstance();
			int iVRTransferSyntax = objITransferSyntax.getVRTransferSyntax();
			objIDataElement = null;
			objReferencedSOPSequence = (ReferencedSOPSequence)objDicomV3Factory.createSequence(0x0008,0x1199, objITransferSyntax, objIDictionaryReader);

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

	/**
	 * Retrieves pre-initialized object of Icon Image 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 IconImageSequence - instance of Icon Image Sequence. 
	 */
	public IconImageSequence getIconImageSequence()
	{
		IconImageSequence objIconImageSequence = null;
		IDataElement objIDataElement =  getDataElement(0x0088,0x0200);
		if(objIDataElement != null)
		{
			IDicomValue objIDicomValue = objIDataElement.getDicomValue();
			if(objIDicomValue != null)
				objIconImageSequence = (IconImageSequence)objIDicomValue;
		}
		else
		{
			DicomV3Factory objDicomV3Factory = DicomV3Factory.createInstance();
			int iVRTransferSyntax = objITransferSyntax.getVRTransferSyntax();
			objIDataElement = null;
			objIconImageSequence = (IconImageSequence)objDicomV3Factory.createSequence(0x0088,0x0200, objITransferSyntax, objIDictionaryReader);

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

	/**
	 * Validates all the attributes in Image Reference 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 Image Reference 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 boolean validate(IDataSet objIDataSet) throws InvalidMacroException
	{
		try
		{
			/*
			 * please refer p.d.f. Chapter 3 page No 798 
			 * 0008,1160  Referenced Frame Number
			 * Required if the Referenced SOP Instance is a multi-frame image and the reference does not apply to all frames.
			 */
			getCompositeObjectReferenceMacro().validate();
		}
		catch( MandatoryMissingException me)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger.getLogger().log(me.getMessage());
			}
			throw new InvalidMacroException(ImageReferenceMacro.class.getSimpleName(),me);
		}
		return true;
	}

	/**
	 * Validates all the attributes in Image Reference 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 boolean validate(IItem objIItem) throws InvalidMacroException
	{
		try
		{
			/*
			 * please refer p.d.f. Chapter 3 page No 798 
			 * 0008,1160  Referenced Frame Number
			 * Required if the Referenced SOP Instance is a multi-frame image and the reference does not apply to all frames.
			 */
			getCompositeObjectReferenceMacro().validate();
		}
		catch( MandatoryMissingException me)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger.getLogger().log(me.getMessage());
			}
			throw new InvalidMacroException(ImageReferenceMacro.class.getSimpleName(),me);
		}
		return true;
	}
}
