/*******************************************************************************
 *  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.dicommodel.modules;


import cdac.medinfo.sdk.dcm30_04.baselibs.DicomV3Factory;
import cdac.medinfo.sdk.dcm30_04.baselibs.DirectoryRecordSequence;
import cdac.medinfo.sdk.dcm30_04.baselibs.Tag;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IDataSet;
import cdac.medinfo.sdk.dcm30_04.commoninterface.ITag;
import cdac.medinfo.sdk.dcm30_04.enums.EnumFileSetConsistencyFlag;

import cdac.medinfo.sdk.dcm30_04.exceptions.InvalidModuleException;
import cdac.medinfo.sdk.dcm30_04.exceptions.ItemLimitException;
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;
import cdac.medinfo.sdk.dcm30_04.utils.SingleCollection;
/**
 \* This module describes Attributes required to define a Directory Information Module.
 */
public class DirectoryInformationModule extends Module
{
	/**
	 * The object of single collection.
	 */
	public static ISingleCollection<ITag> objSingleCollection = null;

	/**
	 * Instantiates a new Directory Information Module.
	 * @param objIDataSet Object of Data Set.
	 */
	public DirectoryInformationModule(IDataSet objIDataSet)
	{
		super(objIDataSet);
	}

	static
	{
		objSingleCollection = new SingleCollection<ITag>();
		objSingleCollection.add(new Tag(0x0004,0x1200));
		objSingleCollection.add(new Tag(0x0004,0x1202));
		objSingleCollection.add(new Tag(0x0004,0x1212));
		objSingleCollection.add(new Tag(0x0004,0x1220));
	}

	/**
	 * Sets Offset of the first byte (of the Item Data Element) of the first 
	 * Directory Record of the Root Directory Entity. This Offset is a 
	 * number of bytes starting with the first byte of the File Meta Information.
	 * When the Root Directory Entity contains no Directory Record, this offset shall be set to 00000000H.
	 * @param iOffsetOfFirstDirectoryRecordOfRootDirectory int value of Offset of the First Directory Record of the Root Directory.
	 */
	public void setOffsetOfFirstDirectoryRecordOfRootDirectoryEntity(int iOffsetOfFirstDirectoryRecordOfRootDirectory)
	{
		/* Accept Offset Of First Directory Record Of Root Directory  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 DataSet
		 */
		addDataElement(0x0004, 0x1200, DicomConstants.DCM_DT_UL, iOffsetOfFirstDirectoryRecordOfRootDirectory);
	}

	/**
	 * Retrieves Offset of the first byte (of the Item Data Element) of the first 
	 * Directory Record of the Root Directory Entity. 
	 * @return int - int value of Offset of the First Directory Record of the Root Directory.
	 */
	public int getOffsetOfFirstDirectoryRecordOfRootDirectoryEntity()
	{
		Object objValue = getValue(0x0004,0x1200);
		if(objValue != null)
			return Integer.parseInt(objValue.toString());
		return DicomConstants.DCM_NO_VALUE;
	}

	/**
	 * Sets Offset of the Last Directory Record of the Root Directory Entity
	 * Offset of the first byte (of the Item Data Element) of the last Directory Record of the Root Directory Entity. 
	 * This Offset is a number of bytes starting with the first byte of the File Meta Information. 
	 * When the Root Directory Entity contains no Directory Record, this offset shall be set to 00000000H.
	 * @param iOffsetOfLastDirectoryRecordOfRootDirectory int value of Offset of the Last Directory Record of the Root Directory.
	 */
	public void setOffsetOfLastDirectoryRecordOfRootDirectoryEntity(int iOffsetOfLastDirectoryRecordOfRootDirectory)
	{
		/* Accept Offset Of Last Directory Record Of Root Directory  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 DataSet
		 */
		addDataElement(0x0004, 0x1202, DicomConstants.DCM_DT_UL, iOffsetOfLastDirectoryRecordOfRootDirectory);
	}

	/**
	 * Retrieves Offset of the first byte (of the Item Data Element) of the last 
	 * Directory Record of the Root Directory Entity. 
	 * @return int - int value of Offset of the last Directory Record of the Root Directory.
	 */
	public int getOffsetOfLastDirectoryRecordOfRootDirectoryEntity()
	{
		Object objValue = getValue(0x0004,0x1202);
		if(objValue != null)
			return Integer.parseInt(objValue.toString());
		return DicomConstants.DCM_NO_VALUE;
	}

	/**
	 * This Flag indicates that an inconsistency within the Directory or 
	 * between the Directory and the Files of the File-set may exist. 
	 * Enumerated Values:
	 * 0000H: no known inconsistencies
	 * FFFFH: the FSR or FSU shall assume that inconsistencies are present.
	 * @param shFileSetConsistencyFlag short value of File Set Consistency Flag.
	 */
	public void setFileSetConsistencyFlag(EnumFileSetConsistencyFlag enumFileSetConsistencyFlag)
	{
		/* Accept File Set Consistency Flag 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 DataSet
		 */
		addDataElement(0x0004, 0x1212, DicomConstants.DCM_DT_US, enumFileSetConsistencyFlag.getValue());
	}

	/**
	 * Retrieves  File Set Consistency Flag.
	 * @return short - short value of File Set Consistency Flag.
	 */
	public short getFileSetConsistencyFlag()
	{
		Object objValue = getValue(0x0004,0x1212);
		if(objValue != null)
			return Short.parseShort(objValue.toString());
		return DicomConstants.DCM_NO_VALUE;
	}

	/**
	 * Retrieves pre-initialized object of Directory Record 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 DirectoryRecordSequence - instance of Directory Record Sequence.
	 */
	public DirectoryRecordSequence getDirectoryRecordSequence()
	{
		DirectoryRecordSequence objDirectoryRecordSequence = (DirectoryRecordSequence)getDicomValue(0x0004,0x1220);
		if(objDirectoryRecordSequence == null)
		{
			/*
			 * If the sequence object is not present in the DataSet, a new sequence object is created and
			 * the TransferSyntax and DictionaryReader is set into it as it is set in the Module. This ensures that 
			 * the DataElements getting added in the DataSet follow the same TransferSyntax and use the same
			 * DictionaryReader object as that of the module.
			 */
			DicomV3Factory objDicomV3Factory = DicomV3Factory.createInstance();
			objDirectoryRecordSequence = (DirectoryRecordSequence)objDicomV3Factory.createSequence(0x0004,0x1220, objITransferSyntax, objIDictionaryReader);
			
			// This will add Data Element of SQ to the DataSet.
			addDataElement(0x0004,0x1220, DicomConstants.DCM_DT_SQ, objDirectoryRecordSequence.getValue());
		}
		return objDirectoryRecordSequence;
	}

	/**
	 * This method validates each Attribute in the Module according to the Type
	 * of the Attribute.Attributes are of 5 types.
	 * Type 1,Type 2 are Mandatory:
	 * Mandatory Attributes have to present in the Module.
	 * Type 1C,2C are Conditional:
	 * Conditional Attributes' presence depend on a condition.
	 * If the condition is satisfied the Attribute has to be present.
	 * Type 3 are Optional
	 * Optional Attributes can be added as and when required.
	 * @return boolean - returns validation status as success or failure
	 * @throws InvalidModuleException - If validation of Module fails
	 */
	public  boolean validateModule() throws InvalidModuleException
	{

		try
		{
			/*
			 * Validation Rules for Mandatory Elements
			 */
			if(!isPresent(0004,1200))
				throw new MandatoryMissingException("0004,1200");
			if(!isPresent(0004,1202))
				throw new MandatoryMissingException("0004,1202");
			if(!isPresent(0004,1212))
				throw new MandatoryMissingException("0004,1212");
			if(!isPresent(0004,1220))
				throw new MandatoryMissingException("0004,1220");
			getDirectoryRecordSequence().validate();
		}
		catch(MandatoryMissingException mme)
		{
			if(DicomConfig.createInstance().isLoggingOn())
				DicomLogger.getLogger().log(mme.getMessage());

			
				throw new InvalidModuleException(this.getClass().getSimpleName(),mme);

		}
		catch(ItemLimitException ile)
		{

			if(DicomConfig.createInstance().isLoggingOn())
				DicomLogger.getLogger().log(ile.getMessage());

			
				throw new InvalidModuleException(this.getClass().getSimpleName(),ile);

		}
		return true;
	}
	/**
	 * This method returns the custom collection containing the list of DataElements belonging to the CT
	 * Image Module specified by DICOM Standard.
	 * 
	 * @return collection - custom collection containing the list of DataElements belonging to the CT Image Module
	 */
	public ISingleCollection<ITag> getVectorOfKeys()
	{
		return objSingleCollection;
	}
}
