/*******************************************************************************
 *  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.InvalidDataTypeException;
import cdac.medinfo.sdk.dcm30_04.exceptions.InvalidMacroException;
import cdac.medinfo.sdk.dcm30_04.exceptions.InvalidSequenceException;
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 Sequence describes the attributes for identifying the general region of the patient anatomy
 * examined using coded terminology, as well as the principal structure(s) within that region that is the target
 * of the current SOP Instance.
 */
public class GeneralAnatomyOptionalMacro extends Macro  
{
	

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	PrimaryAnatomicStructureMacro objPrimaryAnatomicStructureMacro = null;	

	/**
	 * Creates General Anatomy Optical Macro with Default DataSet.
	 * @param objDataSet Collection of DataElements
	 */
	public GeneralAnatomyOptionalMacro(IDataSet objDataSet)
	{
		super(objDataSet);
	}

	/**
	 * Creates General Anatomy Required Macro with Default DataSet and DictionaryReader.
	 * @param objDataSet Collection of DataElements.
	 * @param objDictionaryReader specifies the DICOM Dictionary reader to be used
	 */
	public GeneralAnatomyOptionalMacro(IDataSet objDataSet,IDictionaryReader objDictionaryReader)
	{
		super(objDataSet,objDictionaryReader);
	}

	/**
	 * Creates General Anatomy Required Macro with Default Item.
	 * @param objItem Collection of DataElements in Sequence.
	 */
	public GeneralAnatomyOptionalMacro(IItem objItem)
	{
		super(objItem);
	}

	/**
	 * Creates General Anatomy Required Macro with Default Item and DictionaryReader.
	 * @param objItem  Collection of DataElements in Sequence.
	 * @param objDictionaryReader specifies the DICOM Dictionary reader to be used
	 */
	public GeneralAnatomyOptionalMacro(IItem objItem,IDictionaryReader objDictionaryReader)
	{
		super(objItem, objDictionaryReader);
	}

	/**
	 * Retrieves pre-initialized object of Anatomic Region 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 AnatomicRegionSequence - instance of AnatomicRegionSequence. 
	 */
	public AnatomicRegionSequence getAnatomicRegionSequence()
	{
		AnatomicRegionSequence objAnatomicRegionSequence = null;
		IDataElement objIDataElement =  getDataElement(0x0008,0x2218);
		if(objIDataElement != null)
		{
			IDicomValue objIDicomValue = objIDataElement.getDicomValue();
			if(objIDicomValue != null)
				objAnatomicRegionSequence = (AnatomicRegionSequence)objIDicomValue;
		}
		else
		{
			DicomV3Factory objDicomV3Factory = DicomV3Factory.createInstance();
			int iVRTransferSyntax = objITransferSyntax.getVRTransferSyntax();
			objIDataElement = null;
			objAnatomicRegionSequence = (AnatomicRegionSequence)objDicomV3Factory.createSequence(0x0008,0x2218, objITransferSyntax, objIDictionaryReader);

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

	/**
	 * This method checks for the DataElements of the DataSet according to the General Anatomy Optional Macro
	 * @param objIDataSet object of DataSet for which the the validation is to be done according to the
	 * 						rules of General Anatomy Optional Macro
	 * @return boolean - status of the function as success or failure
	 * @throws InvalidMacroException If Validation of Macro fails.
	 */
	public boolean validate(IDataSet objIDataSet) throws InvalidMacroException
	{
		try
		{
			if(objIDataSet.isPresent(0x0008,0x2218))
			{
				AnatomicRegionSequence objAnatomicRegionSequence = (AnatomicRegionSequence)objIDataSet.getDataForTag(0x0008,0x2218);
				objAnatomicRegionSequence.validate();
			}
			if(PrimaryAnatomicStructureMacro.isMacroPresent(objIDataSet) && !getPrimaryAnatomicStructureMacro().validate(objIDataSet))
				throw new ValidationException(this.getClass().getSimpleName());
		}
		catch( InvalidSequenceException dte)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger.getLogger().log(dte.getMessage());
			}
			throw new InvalidMacroException(this.getClass().getSimpleName(),dte);
		}
		catch( ValidationException dte)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger.getLogger().log(dte.getMessage());
			}
			throw new InvalidMacroException(this.getClass().getSimpleName(),dte);
		}
		return true;
	}

	/**
	 * This method checks if any of the DataElements belonging to this Macro is present in the DataSet.
	 * If such is the case, then the Macro is present in the DataSet.
	 * @param objIDataSet object of DataSet in which the Macro is to be searched 
	 * @return status indicating success or failure
	 */
	public static boolean isMacroPresent(IDataSet objIDataSet)
	{
		if(objIDataSet.isPresent(0x0008, 0x2218) || PrimaryAnatomicStructureMacro.isMacroPresent(objIDataSet))
			return true;
		else 
			return false;
	}

	/**
	 * This method checks if any of the DataElements belonging to this Macro is present in the Item.
	 * If such is the case, then the Macro is present in the Item.
	 * @param objIItem object of Item in which the Macro is to be searched 
	 * @return status indicating success or failure
	 */
	public static boolean isMacroPresent(IItem objIItem)
	{
		if(objIItem.contains(0x0008, 0x2218) || PrimaryAnatomicStructureMacro.isMacroPresent(objIItem))
			return true;
		else 
			return false;
	}

	/**
	 * This method checks for the DataElements of the Item according to the General Anatomy Optional Macro
	 * @param objIItem object of Item for which the the validation is to be done according to the
	 * 						rules of General Anatomy Optional Macro
	 * @return boolean- status of the function as success or failure
	 * @throws InvalidMacroException
	 */
	public boolean validate(IItem objIItem) throws InvalidMacroException
	{
		try
		{
			if(objIItem.contains(0x0008,0x2218))
			{
				AnatomicRegionSequence objAnatomicRegionSequence = (AnatomicRegionSequence)objIItem.getDataForTag(0x0008,0x2218);
				objAnatomicRegionSequence.validate();
			}
			if(PrimaryAnatomicStructureMacro.isMacroPresent(objIItem) && !getPrimaryAnatomicStructureMacro().validate(objIItem))
				return false;
		}
		catch( ValidationException ve)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger.getLogger().log(ve.getMessage());
			}
			throw new InvalidMacroException(this.getClass().getSimpleName(),ve);
		}
		catch( InvalidDataTypeException de)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger.getLogger().log(de.getMessage());
			}
			throw new InvalidMacroException(this.getClass().getSimpleName(),de);
		}
		return true;
	}

	/**
	 * Return the Primary Anatomic Structure Macro instance.
	 * @return - instance of PrimaryAnatomicStructureMacro.
	 */
	public 	PrimaryAnatomicStructureMacro getPrimaryAnatomicStructureMacro()
	{
		if(objPrimaryAnatomicStructureMacro == null)
		{
			if(iMacroLevel == DicomConstants.DCM_MODULE_LEVEL_MACRO)
				objPrimaryAnatomicStructureMacro = new PrimaryAnatomicStructureMacro(objIDataSet);
			else 
				objPrimaryAnatomicStructureMacro = new PrimaryAnatomicStructureMacro(objIItem);

			return objPrimaryAnatomicStructureMacro;
		}
		return objPrimaryAnatomicStructureMacro;
	}

	/**
	 * Validates all the attributes in CodeSequenceMacro
	 * @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;
	}
}
