/*******************************************************************************
 *  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.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 Macro allows Digital Signatures to be included in a DICOM Data Set for the purpose of
 * insuring the integrity of the Data Set, and to authenticate the sources of the Data Set.
 */
public class DigitalSignaturesMacro extends Macro  
{
	

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

	/**
	 * This constructor sets the DataSet as the DataHolder for this Macro.
	 * It also sets the TransferSyntax,DictionaryReader as the same as in DataSet.
	 * @param objDataSet Collection of DataElements.
	 */
	public DigitalSignaturesMacro(IDataSet objDataSet)
	{
		super(objDataSet);
	}

	/**
	 * This constructor sets the Dataset and the specified dictionaryReader into the Macro
	 * It also sets the transfersyntax as same as in Dataset.
	 * @param objDataSet Collection of DataElements
	 * @param objDictionaryReader specifies the DICOM Dictionary reader to be used. 
	 */
	public DigitalSignaturesMacro(IDataSet objDataSet,IDictionaryReader objDictionaryReader)
	{
		super(objDataSet,objDictionaryReader);
	}

	/**
	 * This constructor sets the Item as the DataHolder for this Macro.
	 * It also sets the TransferSyntax,DictionaryReader as the same as in Item.
	 * @param objItem collection of data elements in a sequence.
	 */
	public DigitalSignaturesMacro(IItem objItem)
	{
		super(objItem);
	}

	/**
	 * This constructor sets the Item and the specified dictionaryReader into the Macro
	 * It also sets the transfersyntax as same as in Item.
	 * @param objItem collection of data elements in a sequence.
	 * @param objDictionaryReader specifies the DICOM Dictionary reader to be used.
	 */
	public DigitalSignaturesMacro(IItem objItem,IDictionaryReader objDictionaryReader)
	{
		super(objItem, objDictionaryReader);
	}

	/**
	 * Retrieves pre-initialized object of MAC Parameters 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 MACParametersSequence - instance of MACParametersSequence. 
	 */
	public MACParametersSequence getMACParametersSequence()
	{
		MACParametersSequence objMACParametersSequence = null;
		IDataElement objIDataElement =  getDataElement(0x4FFE,0x0001);
		if(objIDataElement != null)
		{
			IDicomValue objIDicomValue = objIDataElement.getDicomValue();
			if(objIDicomValue != null)
				objMACParametersSequence = (MACParametersSequence)objIDicomValue;
		}
		else
		{
			DicomV3Factory objDicomV3Factory = DicomV3Factory.createInstance();
			int iVRTransferSyntax = objITransferSyntax.getVRTransferSyntax();
			objIDataElement = null;
			objMACParametersSequence = (MACParametersSequence)objDicomV3Factory.createSequence(0x4FFE,0x0001, objITransferSyntax, objIDictionaryReader);

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

	/**
	 * Retrieves pre-initialized object of Digital Signatures 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 DigitalSignaturesSequence - instance of DigitalSignaturesSequence. 
	 */
	public DigitalSignaturesSequence getDigitalSignaturesSequence()
	{
		DigitalSignaturesSequence objDigitalSignaturesSequence = null;
		IDataElement objIDataElement =  getDataElement(0xFFFA,0xFFFA);
		if(objIDataElement != null)
		{
			IDicomValue objIDicomValue = objIDataElement.getDicomValue();
			if(objIDicomValue != null)
				objDigitalSignaturesSequence = (DigitalSignaturesSequence)objIDicomValue;
		}
		else
		{
			DicomV3Factory objDicomV3Factory = DicomV3Factory.createInstance();
			int iVRTransferSyntax = objITransferSyntax.getVRTransferSyntax();
			objIDataElement = null;
			objDigitalSignaturesSequence = (DigitalSignaturesSequence)objDicomV3Factory.createSequence(0xFFFA,0xFFFA, objITransferSyntax, objIDictionaryReader);

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

	/**
	 * Validates all the attributes in AcquisitionContextSequenceItem that are present in the DataSet
	 * @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 true;
	}

	/**
	 * This method checks for the DataElements of the DataSet according to the Digital Signatures Macro
	 * @param objIDataSet object of DataSet for which the the validation is to be done according to the
	 * 						rules of Digital Signatures Macro
	 * @return boolean - status of the function as success or failure
	 * @throws InvalidMacroException  Signals Macro Validation is failed.
	 */
	public boolean validate(IDataSet objIDataSet) throws InvalidMacroException
	{
		try
		{
			if(objIDataSet.isPresent(0x4FFE,0x0001))
				getMACParametersSequence().validate();
			if(objIDataSet.isPresent(0xFFFA,0xFFFA))
				getDigitalSignaturesSequence().validate();
		}
		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;
	}

	/**
	 * This method checks for the DataElements of the Item according to the Digital Signatures Macro
	 * @param objIItem object of Item for which the the validation is to be done according to the
	 * 						rules of Digital Signatures Macro
	 * @return - status of the function as success or failure
	 * @throws InvalidMacroException Signals Macro Validation is failed.
	 */
	public boolean validate(IItem objIItem) throws InvalidMacroException
	{
		try{
			if(objIItem.contains(0x4FFE,0x0001))
				getMACParametersSequence().validate();
			if(objIItem.contains(0xFFFA,0xFFFA))
				getDigitalSignaturesSequence().validate();
		}
		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;
	}
}
