/*******************************************************************************
 *  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.IDictionaryReader;
import cdac.medinfo.sdk.dcm30_04.commoninterface.ITransferSyntax;
import cdac.medinfo.sdk.dcm30_04.exceptions.ConditionFailedException;
import cdac.medinfo.sdk.dcm30_04.exceptions.InvalidItemException;
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;

import cdac.medinfo.sdk.dcm30_04.utils.ISingleCollection;


/**
 * A Sequence holding one or more Digital Signatures.
 */
public class DigitalSignaturesSequenceItem extends Item  
{
	

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

	/**
	 * This constructor creates the item and with default TransferSyntax 
	 */
	DigitalSignaturesSequenceItem()
	{
		super();
	}

	/*
	 * This constructor calls the respective superclass constructor
	 * This constructor should throw exception if null TS is tried to be set
	 */
	/**
	 * This constructor creates the item with default TransferSyntax.
	 * @param objTransferSyntax specifies the DICOM Standard defined TransfeSyntax  
	 */
	DigitalSignaturesSequenceItem(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 
	 */
	DigitalSignaturesSequenceItem(ITransferSyntax objTransferSyntax, IDictionaryReader objDictionaryReader)
	{
		super(objTransferSyntax,objDictionaryReader);
	}

	/**
	 * Sets a number used to identify which MAC Parameters Sequence item was used in the calculation of this Digital Signature.
	 * @param shMACIDNumber short value of MAC ID Number.
	 */
	public void setMACIDNumber(short shMACIDNumber)
	{
		/* Accept the MAC ID Number in String format of type US.
		 * 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(0x0400, 0x0005, shMACIDNumber,getDictionaryReader());
		else
			objIDataElement = new ExplicitDE(0x0400, 0x0005,DicomConstants.DCM_DT_US, shMACIDNumber);

		addDataElement(objIDataElement);
	}

	/**
	 * Retrieves a number used to identify which MAC Parameters Sequence item.
	 * @return short - short value of MAC ID Number.
	 */
	public short getMACIDNumber()
	{
		Object objValue = getValue(0x0400,0x0005);
		if(objValue != null)
			return Short.parseShort(objValue.toString());
		return DicomConstants.DCM_NO_VALUE;
	}

	/**
	 * Sets a UID that can be used to uniquely reference this signature.
	 * @param strDigitalSignatureUID String value of Digital Signature UID.
	 */
	public void setDigitalSignatureUID(String strDigitalSignatureUID)
	{
		/*Accept the Digital Signature UID in String format of type UI.
		 * 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(0x0400, 0x0100, strDigitalSignatureUID,getDictionaryReader());
		else
			objIDataElement = new ExplicitDE(0x0400, 0x0100,DicomConstants.DCM_DT_UI, strDigitalSignatureUID);

		addDataElement(objIDataElement);
	}

	/**
	 * Retrieves a UID that can be used to uniquely reference this signature.
	 * @return String - value of Digital Signature UID.
	 */
	public String getDigitalSignatureUID()
	{
		Object objValue = getValue(0x0400, 0x0100);
		if(objValue != null)
			return objValue.toString();
		return null;
	}

	/**
	 * Sets the date and time the Digital Signature was created. The time shall include an offset (i.e.,
	 * time zone indication) from Coordinated Universal Time.
	 * @param strDigitalSignatureDateTime String value of Digital Signature DateTime.
	 */
	public void setDigitalSignatureDateTime(String strDigitalSignatureDateTime)
	{
		/*Accept the Digital Signature DateTime in String format 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(0x0400, 0x0105, strDigitalSignatureDateTime,getDictionaryReader());
		else
			objIDataElement = new ExplicitDE(0x0400, 0x0105,DicomConstants.DCM_DT_DT, strDigitalSignatureDateTime);

		addDataElement(objIDataElement);
	}

	/**
	 * Retrieves date and time the Digital Signature was created.
	 * @return String - value of Digital Signature DateTime.
	 */
	public String getDigitalSignatureDateTime()
	{
		Object objValue = getValue(0x0400,0x0105);
		if(objValue != null)
			return objValue.toString();
		return null;
	}

	/**
	 * Sets the type of certificate used in (0400,0115).
	 * @param strCertificateType String value of Certificate Type.
	 */
	public void setCertificateType(String strCertificateType)
	{
		/*Accept the Certificate 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(0x0400, 0x0110, strCertificateType,getDictionaryReader());
		else
			objIDataElement = new ExplicitDE(0x0400, 0x0110,DicomConstants.DCM_DT_CS, strCertificateType);

		addDataElement(objIDataElement);
	}

	/**
	 * Retrieves the type of certificate used in (0400,0115).
	 * @return String - value of Certificate Type.
	 */
	public String getCertificateType()
	{
		Object objValue = getValue(0x0400,0x0110);
		if(objValue != null)
			return objValue.toString();
		return null;
	}

	/**
	 * Sets a certificate that holds the identity of the entity producing this Digital Signature, that entity�s
	 * public key or key identifier, and the algorithm and associated parameters with which that
	 * public key is to be used.
	 * @param vectCertificateOfSigner Collection of byte array of Certificate Of Signer values.
	 */
	public void setCertificateOfSigner(ISingleCollection<byte[]> vectCertificateOfSigner)
	{
		/*Accept the Certificate Of Signer in vector of byte array format of type OB.
		 * 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(0x0400, 0x0115, vectCertificateOfSigner,getDictionaryReader());
		else
			objIDataElement = new ExplicitDE(0x0400, 0x0115,DicomConstants.DCM_DT_OB, vectCertificateOfSigner);

		addDataElement(objIDataElement);
	}

	/**
	 * Retrieves a certificate that holds the identity of the entity producing this Digital Signature, that entity�s
	 * public key or key identifier, and the algorithm and associated parameters with which that
	 * public key is to be used.
	 * @return ISingleCollection<byte[]> -  collection of byte array of Certificate Of Signer values.
	 */
	@SuppressWarnings("unchecked")
	public ISingleCollection<byte[]> getCertificateOfSigner()
	{
		Object objValue = getValue(0x0400, 0x0115);
		if(objValue != null)
			return (ISingleCollection<byte[]>)objValue;
		return null;
	}

	/**
	 * Sets the MAC generated and encrypted using the algorithm,parameters, and private key associated with
	 * the Certificate of the Signer (0400,0115).
	 * @param vectSignature collection of byte array of Signature values.
	 */
	public void setSignature(ISingleCollection<byte[]> vectSignature)
	{
		/*Accept the Signature in vector of byte array format of type OB.
		 * 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(0x0400, 0x0120, vectSignature,getDictionaryReader());
		else
			objIDataElement = new ExplicitDE(0x0400, 0x0120,DicomConstants.DCM_DT_OB, vectSignature);

		addDataElement(objIDataElement);
	}

	/**
	 * Retrieves the MAC generated and encrypted using the algorithm,parameters, and private key associated with
	 * the Certificate of the Signer (0400,0115).
	 * @return ISingleCollection<byte[]> - collection of byte array of Signature values.
	 */
	@SuppressWarnings("unchecked")
	public ISingleCollection<byte[]> getSignature()
	{
		Object objValue = getValue(0x0400, 0x0120);
		if(objValue != null)
			return (ISingleCollection<byte[]>)objValue;
		return null;
	}

	/**
	 * Sets the type of certified timestamp used in the Certified Timestamp (0400,0310) Attribute.
	 * Required if Certified Timestamp (0400,0310) is present.
	 * @param strCertifiedTimestampType String value of Certified Timestamp Type.
	 */
	public void setCertifiedTimestampType(String strCertifiedTimestampType)
	{
		/*Accept the Certified Timestamp 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(0x0400, 0x0305, strCertifiedTimestampType,getDictionaryReader());
		else
			objIDataElement = new ExplicitDE(0x0400, 0x0305,DicomConstants.DCM_DT_CS, strCertifiedTimestampType);

		addDataElement(objIDataElement);
	}

	/**
	 * Retrieves the type of certified timestamp used in the Certified Timestamp (0400,0310) Attribute.
	 * @return String - value of Certified Timestamp Type.
	 */
	public String getCertifiedTimestampType()
	{
		Object objValue = getValue(0x0400, 0x0305);
		if(objValue != null)
			return objValue.toString();
		return null;
	}

	/**
	 * Sets a certified timestamp of the Digital Signature (0400,0120) Attribute Value, which shall be
	 * obtained when the Digital Signature is created. 
	 * @param vectCertifiedTimestamp collection of byte array of Certified Timestamp
	 */
	public void setCertifiedTimestamp(ISingleCollection<byte[]> vectCertifiedTimestamp)
	{
		/* Accept the Certified Timestamp in vector of byte array format of type OB.
		 * 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(0x0400, 0x0310, vectCertifiedTimestamp,getDictionaryReader());
		else
			objIDataElement = new ExplicitDE(0x0400, 0x0310,DicomConstants.DCM_DT_OB, vectCertifiedTimestamp);

		addDataElement(objIDataElement);
	}

	/**
	 * Retrieves a certified timestamp of the Digital Signature (0400,0120) Attribute Value, which shall be
	 * obtained when the Digital Signature is created. 
	 * @return ISingleCollection<byte[]> - collection of byte array of certified timestamp values.
	 */
	@SuppressWarnings("unchecked")
	public ISingleCollection<byte[]> getCertifiedTimestamp()
	{
		Object objValue = getValue(0x0400, 0x0310);
		if(objValue != null)
			return (ISingleCollection<byte[]>)objValue;
		return null;
	}

	/**
	 * Validates all the attributes in Digital Signatures Sequence Item 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();
			if(!contains(0x0400,0x0005)) 
				throw new MandatoryMissingException("0400,0005");
			else if(!contains(0x0400,0x0100))
				throw new MandatoryMissingException("0400,0100");
			else if(!contains(0x0400,0x0105))	
				throw new MandatoryMissingException("0400,0105");
			else if(!contains(0x0400,0x0110))	
				throw new MandatoryMissingException("0400,0110");
			else if(!contains(0x0400,0x0115))
				throw new MandatoryMissingException("0400,0115");
			else if(!contains(0x0400,0x0120))	
				throw new MandatoryMissingException("0400,0120");
			else if(contains(0x0400,0x0305) && !contains(0x0400,0x0310))
				throw new ConditionFailedException("conditional Element 0400,0310 required for Tag 0400,0x0305") ;

		}
		catch(MandatoryMissingException me)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger.getLogger().log(me.getMessage());
			}
			throw new InvalidItemException(this.getClass().getSimpleName(),me);
		}
		catch( ConditionFailedException ce)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger.getLogger().log(ce.getMessage());
			}
			throw new InvalidItemException(this.getClass().getSimpleName(),ce);
		}
		return true;
	}
}
