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

import java.io.IOException;
import java.util.Locale;

import cdac.medinfo.sdk.dcm30_04.baselibs.ContentSequence;
import cdac.medinfo.sdk.dcm30_04.baselibs.ContentSequenceItem;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IDataSet;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IDicomStream;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IDictionaryReader;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IItem;
import cdac.medinfo.sdk.dcm30_04.commoninterface.ITransferSyntax;
import cdac.medinfo.sdk.dcm30_04.dicommodel.modules.ClinicalTrialSeriesModule;
import cdac.medinfo.sdk.dcm30_04.dicommodel.modules.EnhancedGeneralEquipmentModule;
import cdac.medinfo.sdk.dcm30_04.dicommodel.modules.GeneralEquipmentModule;
import cdac.medinfo.sdk.dcm30_04.dicommodel.modules.GeneralStudyModule;
import cdac.medinfo.sdk.dcm30_04.dicommodel.modules.NonImageIOD;
import cdac.medinfo.sdk.dcm30_04.dicommodel.modules.PatientModule;
import cdac.medinfo.sdk.dcm30_04.dicommodel.modules.PatientStudyModule;
import cdac.medinfo.sdk.dcm30_04.dicommodel.modules.SOPCommonModule;
import cdac.medinfo.sdk.dcm30_04.dicommodel.modules.SRDocumentContentModule;
import cdac.medinfo.sdk.dcm30_04.dicommodel.modules.SRDocumentGeneralModule;
import cdac.medinfo.sdk.dcm30_04.dicommodel.modules.SRDocumentSeriesModule;
import cdac.medinfo.sdk.dcm30_04.dicommodel.modules.SynchronizationModule;
import cdac.medinfo.sdk.dcm30_04.enums.EnumModuleNames;
import cdac.medinfo.sdk.dcm30_04.enums.EnumSOPClassUIDs;

import cdac.medinfo.sdk.dcm30_04.enums.EnumValueType;
import cdac.medinfo.sdk.dcm30_04.exceptions.ConditionFailedException;
import cdac.medinfo.sdk.dcm30_04.exceptions.InvalidIODException;
import cdac.medinfo.sdk.dcm30_04.exceptions.InvalidModuleException;
import cdac.medinfo.sdk.dcm30_04.exceptions.ParseException;
import cdac.medinfo.sdk.dcm30_04.utils.DicomConfig;
import cdac.medinfo.sdk.dcm30_04.utils.DicomLogger;
import cdac.medinfo.sdk.dcm30_04.utils.ICollectionIterator;
import cdac.medinfo.sdk.dcm30_04.utils.ResourceBundleWrapper;
/**
 * The Macular Grid Thickness and Volume Report IOD is used to represent the macular grid thickness and volume values derived from ophthalmic images.
 * @author saloni
 *
 */
public class MacularGridThicknessandVolumeReportIOD extends NonImageIOD
{

	/**
	 * The Constant ENHANCED_SR_IOD.
	 */
	public static final String MASCULAR_GRID_THICKNESS_AND_VOLUME_REPORT_IOD = "Macular Grid Thickness and Volume Report IOD";

	/**
	 * The obj patient module.
	 */
	PatientModule objPatientModule = null;

	/**
	 * The obj general study module.
	 */
	GeneralStudyModule objGeneralStudyModule = null;

	/**
	 * The obj patient study module.
	 */
	PatientStudyModule objPatientStudyModule = null;

	/**
	 * The obj sr document series module.
	 */
	SRDocumentSeriesModule objSRDocumentSeriesModule = null;

	/**
	 * The obj clinical trial series module.
	 */
	ClinicalTrialSeriesModule objClinicalTrialSeriesModule = null;

	/**
	 * The obj general equipment module.
	 */
	GeneralEquipmentModule objGeneralEquipmentModule = null;
	/**
	 *  The obj Enhanced General Equipment module.
	 */
	EnhancedGeneralEquipmentModule objEnhancedGeneralEquipmentModule= null;

	/**
	 * The obj sr document general module.
	 */
	SRDocumentGeneralModule objSRDocumentGeneralModule = null;

	/**
	 * The obj sr document content module.
	 */
	SRDocumentContentModule objSRDocumentContentModule = null;

	/**
	 * The obj sop common module.
	 */
	SOPCommonModule objSOPCommonModule = null;

	/**
	 * Instantiates a new MacularGridThicknessandVolumeReportIOD
	 */
	public MacularGridThicknessandVolumeReportIOD()
	{
		super();
	}

	/**
	 * This constructor initializes the TransferSyntax  in its superclass IOD.
	 * 
	 * @param objITransferSyntax_ - specifies the DICOM Standard defined TransfeSyntax.
	 */
	public MacularGridThicknessandVolumeReportIOD(ITransferSyntax objITransferSyntax_)
	{
		super(objITransferSyntax_);
	}

	/**
	 * This constructor initializes the  DictionaryReader
	 * in its superclass IOD.
	 * 
	 * @param objIDictionaryReader_ - specifies the DICOM Dictionary reader to be used .
	 */
	public MacularGridThicknessandVolumeReportIOD(IDictionaryReader objIDictionaryReader_)
	{
		super(objIDictionaryReader_);
	}

	/**
	 * This constructor accepts the DataSet from the user   in its superclass IOD.
	 * 
	 * @param objIDataSet_ - specifies the data set to be set in the IOD.
	 */
	public MacularGridThicknessandVolumeReportIOD(IDataSet objIDataSet_)
	{
		super(objIDataSet_);
	}

	/**
	 * This constructor initializes the TransferSyntax and DictionaryReader in its super class IOD.
	 * 
	 * @param objITransferSyntax_ specifies the DICOM Standard defined TransfeSyntax.
	 * @param objIDictionaryReader_ specifies the DICOM Dictionary reader to be used .
	 */
	public MacularGridThicknessandVolumeReportIOD(ITransferSyntax objITransferSyntax_,IDictionaryReader objIDictionaryReader_)
	{
		super(objITransferSyntax_,objIDictionaryReader_);
	}

	/**
	 * Creates MacularGridThicknessandVolumeReportIOD IOD from a DICOM file containing MacularGridThicknessandVolumeReportIOD DICOM data.
	 * @param strFileName DICOM File with absolute path.
	 * @throws IOException Exception caused due to wrong I/O operations. 
	 * @throws ParseException signals if some parse exceptions are occurred.
	 * @throws InvalidIODException signals if some IOD exceptions are occurred.
	 */
	public MacularGridThicknessandVolumeReportIOD(String strFileName)throws IOException,InvalidIODException
	{
		super(strFileName);
		try
		{
			if(objIDataSet != null)
			{
				String strSOPClassUID = objIDataSet.getSOPClassUID();
				if(strSOPClassUID != null)
				{
					if(!strSOPClassUID.equals(EnumSOPClassUIDs.MACULARGRIDTHICKNESSANDVOLUMEREPORTIOD.getValue()))
					{
						throw new InvalidIODException(ResourceBundleWrapper.getValue("exceptions", "InvalidIOD.FileNotMatched", new Locale(DicomConfig.createInstance().getLocale())) + MASCULAR_GRID_THICKNESS_AND_VOLUME_REPORT_IOD);
					}
				}
				strSOPClassUID = null;
			}
		}
		catch(InvalidIODException iie)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger.getLogger().log(iie.getMessage());
			}
			throw iie;
		}
	}

	/**
	 * Retrieves pre-initialized instance of PatientModule. Creates a new instance
	 * if no pre-existing module instance is available.If previously created instance is
	 * present then returns the same module instance.
	 * 
	 * @return PatientModule - instance of {@link PatientModule}.
	 */
	public PatientModule getPatientModule() 
	{
		if(objPatientModule == null)
		{
			objPatientModule = new PatientModule(objIDataSet);
			return objPatientModule;
		}
		return objPatientModule;
	}

	/**
	 * Retrieves pre-initialized instance of GeneralStudyModule. Creates a new instance
	 * if no pre-existing module instance is available.If previously created instance is
	 * present then returns the same module instance.
	 * 
	 * @return GeneralStudyModule - instance of {@link GeneralStudyModule}.
	 */
	public GeneralStudyModule getGeneralStudyModule() 
	{
		if(objGeneralStudyModule == null)
		{
			objGeneralStudyModule = new GeneralStudyModule(objIDataSet);
			return objGeneralStudyModule;
		}
		return objGeneralStudyModule;
	}

	/**
	 * Retrieves pre-initialized instance of PatientStudyModule. Creates a new instance
	 * if no pre-existing module instance is available.If previously created instance is
	 * present then returns the same module instance.
	 * 
	 * @return PatientStudyModule - instance of {@link PatientStudyModule}.
	 */
	public PatientStudyModule getPatientStudyModule() 
	{
		if(objPatientStudyModule == null)
		{
			objPatientStudyModule = new PatientStudyModule(objIDataSet);
			return objPatientStudyModule;
		}
		return objPatientStudyModule;
	}

	/**
	 * Retrieves pre-initialized instance of ClinicalTrialSeriesModule. Creates a new instance
	 * if no pre-existing module instance is available.If previously created instance is
	 * present then returns the same module instance.
	 * 
	 * @return ClinicalTrialSeriesModule - instance of {@link ClinicalTrialSeriesModule}.
	 */
	public ClinicalTrialSeriesModule getClinicalTrialSeriesModule() 
	{
		if(objClinicalTrialSeriesModule == null)
		{
			objClinicalTrialSeriesModule = new ClinicalTrialSeriesModule(objIDataSet);
			return objClinicalTrialSeriesModule;
		}
		return objClinicalTrialSeriesModule;
	}

	/**
	 * Retrieves pre-initialized instance of GeneralEquipmentModule. Creates a new instance
	 * if no pre-existing module instance is available.If previously created instance is
	 * present then returns the same module instance.
	 * 
	 * @return GeneralEquipmentModule - instance of {@link GeneralEquipmentModule}.
	 */
	public GeneralEquipmentModule getGeneralEquipmentModule() 
	{
		if(objGeneralEquipmentModule == null)
		{
			objGeneralEquipmentModule = new GeneralEquipmentModule(objIDataSet);
			return objGeneralEquipmentModule;
		}
		return objGeneralEquipmentModule;
	}
	/**
	 * Retrieves pre-initialized instance of Enhanced General Equipment Module. Creates a new instance
	 * if no pre-existing module instance is available.If previously created instance is
	 * present then returns the same module instance.
	 * 
	 * @return EnhancedGeneralEquipmentModule - instance of {@link EnhancedGeneralEquipmentModule}.
	 */
	public EnhancedGeneralEquipmentModule getEnhancedGeneralEquipmentModule()
	{
		if(objEnhancedGeneralEquipmentModule == null)
		{
			objEnhancedGeneralEquipmentModule = new EnhancedGeneralEquipmentModule(objIDataSet);
			return objEnhancedGeneralEquipmentModule;
		}
		return objEnhancedGeneralEquipmentModule;
	}

	/**
	 * Retrieves pre-initialized instance of SOPCommonModule. Creates a new instance
	 * if no pre-existing module instance is available.If previously created instance is
	 * present then returns the same module instance.
	 * 
	 * @return SOPCommonModule - instance of {@link SOPCommonModule}.
	 */
	public SOPCommonModule getSOPCommonModule() 
	{
		if(objSOPCommonModule == null)
		{
			objSOPCommonModule = new SOPCommonModule(objIDataSet);
			return objSOPCommonModule;
		}
		return objSOPCommonModule;
	}

	/**
	 * Retrieves pre-initialized instance of SRDocumentSeriesModule. Creates a new instance
	 * if no pre-existing module instance is available.If previously created instance is
	 * present then returns the same module instance.
	 * 
	 * @return SRDocumentSeriesModule - instance of {@link SRDocumentSeriesModule}.
	 */
	public SRDocumentSeriesModule getSRDocumentSeriesModule() 
	{
		if(objSRDocumentSeriesModule == null)
		{
			objSRDocumentSeriesModule = new SRDocumentSeriesModule(objIDataSet);
			return objSRDocumentSeriesModule;
		}
		return objSRDocumentSeriesModule;
	}

	/**
	 * Retrieves pre-initialized instance of SRDocumentGeneralModule. Creates a new instance
	 * if no pre-existing module instance is available.If previously created instance is
	 * present then returns the same module instance.
	 * 
	 * @return SRDocumentGeneralModule - instance of {@link SRDocumentGeneralModule}.
	 */
	public SRDocumentGeneralModule getSRDocumentGeneralModule() 
	{
		if(objSRDocumentGeneralModule == null)
		{
			objSRDocumentGeneralModule = new SRDocumentGeneralModule(objIDataSet);
			return objSRDocumentGeneralModule;
		}
		return objSRDocumentGeneralModule;
	}

	/**
	 * Retrieves pre-initialized instance of SRDocumentContentModule. Creates a new instance
	 * if no pre-existing module instance is available.If previously created instance is
	 * present then returns the same module instance.
	 * 
	 * @return SRDocumentContentModule - instance of {@link SRDocumentContentModule}.
	 */
	public SRDocumentContentModule getSRDocumentContentModule() 
	{
		if(objSRDocumentContentModule == null)
		{
			objSRDocumentContentModule = new SRDocumentContentModule(objIDataSet);
			return objSRDocumentContentModule;
		}
		return objSRDocumentContentModule;
	}

	/**
	 * This method validates Non-Image IOD ExtensibleSRIOD according to the Module Table given in The DICOM Standard.
	 * The validate method fails if one of the mandatory modules are absent or any of the
	 * modules are invalid. The validate method also checks for conditional modules.
	 * 
	 * @return boolean - status of validation as success or failure
	 * 
	 * @throws InvalidIODException  throws when the IOD is invalid.
	 */
	public boolean validate() throws InvalidIODException
	{
		try
		{
			super.validate();

			/*Validate the mandatory elements*/
			getPatientModule().validateModule();
			getGeneralStudyModule().validateModule();
			getSRDocumentSeriesModule().validateModule();
			getGeneralEquipmentModule().validateModule();
			getEnhancedGeneralEquipmentModule().validateModule();
			getSRDocumentGeneralModule().validateModule();
			getSRDocumentContentModule().validateModule();
			getSOPCommonModule().validateModule();

			/*
			 * This condition checks for IOD's User Optional/Conditional modules validation
			 */
			if(isModulePresent(PatientStudyModule.objSingleCollection, objIDataSet))
				getPatientStudyModule().validateModule();
			if(isModulePresent(ClinicalTrialSeriesModule.objSingleCollection, objIDataSet))
				getClinicalTrialSeriesModule().validateModule();


			/*
			 * Validation of constraints
			 */
			ContentSequence objContentSequence = getSRDocumentContentModule().getDocumentRelationshipMacro().getContentSequence();
			if(objContentSequence!=null)
			{
				ICollectionIterator<IItem> objContentSequenceIterator = objContentSequence.iterator();
				ContentSequenceItem objContentSequenceItem = null;
				String strValueType = null;
				while(objContentSequenceIterator.hasNext())
				{
					objContentSequenceItem = (ContentSequenceItem)objContentSequenceIterator.next();
					strValueType = objContentSequenceItem.getDocumentContentMacro().getValueType();
					if(!((EnumValueType.TEXT.getValue().equals(strValueType)) || (EnumValueType.CODE.getValue().equals(strValueType)) || (EnumValueType.NUM.getValue().equals(strValueType)) ||
							(EnumValueType.DATETIME.getValue().equals(strValueType)) || (EnumValueType.DATE.getValue().equals(strValueType)) ||
							(EnumValueType.TIME.getValue().equals(strValueType)) || (EnumValueType.UIDREF.getValue().equals(strValueType)) ||
							(EnumValueType.PNAME.getValue().equals(strValueType)) || (EnumValueType.SCOORD.getValue().equals(strValueType)) || (EnumValueType.TCOORD.getValue().equals(strValueType)) || 
							(EnumValueType.COMPOSITE.getValue().equals(strValueType)) || (EnumValueType.IMAGE.getValue().equals(strValueType)) || (EnumValueType.WAVEFORM.getValue().equals(strValueType)) ||
							(EnumValueType.CONTAINER.getValue().equals(strValueType))))
						throw new InvalidIODException("Element 0040,A040 is constrained to the following Values " + EnumValueType.TEXT.getValue()
								+ " or " + EnumValueType.CODE.getValue()+ " or " + EnumValueType.NUM.getValue()+ " or " + EnumValueType.DATETIME.getValue()
								+ " or " + EnumValueType.DATE.getValue()+ " or " + EnumValueType.TIME.getValue()
								+ " or " + EnumValueType.UIDREF.getValue()+ " or " + EnumValueType.PNAME.getValue()+ " or " + EnumValueType.SCOORD.getValue()
								+ " or " + EnumValueType.TCOORD.getValue()+ " or " + EnumValueType.COMPOSITE.getValue() + " or " + EnumValueType.IMAGE.getValue()
								+ " or " + EnumValueType.WAVEFORM.getValue()+ " or " + EnumValueType.CONTAINER.getValue());
					int[] lArrReferencedContentItemIdentifier = objContentSequenceItem.getReferencedContentItemIdentifier();
					/*
					 * if Referenced Content Item Identifier (0040,DB73) not present relation ship type is by- value.
					 * Please refer Note on p.d.f. Chapter 3 page No 168.
					 */
					if(lArrReferencedContentItemIdentifier != null)
						throw new InvalidIODException("Relationships by-reference are forbidden in this IOD");
				}
			}
			/*
			 * Condition for constraints validation are  not clear
			 * Relationship Constraints
			 * Hence not validated.
			 * Refer p.d.f Chapter 3
			 * Page No :- 170
			 */
		}
		catch(ConditionFailedException cfe)
		{
			if(DicomConfig.createInstance().isLoggingOn())
				DicomLogger.getLogger().log(cfe.getMessage());
			throw new InvalidIODException(MASCULAR_GRID_THICKNESS_AND_VOLUME_REPORT_IOD,cfe);
		}
		catch(InvalidModuleException ime)
		{
			if(DicomConfig.createInstance().isLoggingOn())
				DicomLogger.getLogger().log(ime.getMessage());
			
				throw new InvalidIODException(MASCULAR_GRID_THICKNESS_AND_VOLUME_REPORT_IOD,ime);
		}
		return true;
	}

	/**
	 *  Dumps the Name of IOD,Module and corresponding Attributes of Module.
	 *  @param objIDicomStream - the Stream on which the Data is to be written.
	 *  @throws IOException - Exception is thrown indicating runtime failure of writing operation.
	 */
	public void dumpDICOMInfo(IDicomStream objIDicomStream) throws IOException
	{
		objIDicomStream.writeString(MASCULAR_GRID_THICKNESS_AND_VOLUME_REPORT_IOD + "\n");
		super.dumpDICOMInfo(objIDicomStream);

		objIDicomStream.writeString("\t" + getPatientModule().getClass().getSimpleName() + "\n");
		getPatientModule().dumpDICOMInfo(objIDicomStream);

		objIDicomStream.writeString("\t" + getGeneralStudyModule().getClass().getSimpleName() + "\n");
		getGeneralStudyModule().dumpDICOMInfo(objIDicomStream);

		objIDicomStream.writeString("\t" + getPatientStudyModule().getClass().getSimpleName() + "\n");
		getPatientStudyModule().dumpDICOMInfo(objIDicomStream);

		objIDicomStream.writeString("\t" + getSRDocumentSeriesModule().getClass().getSimpleName() + "\n");
		getSRDocumentSeriesModule().dumpDICOMInfo(objIDicomStream);

		objIDicomStream.writeString("\t" + getClinicalTrialSeriesModule().getClass().getSimpleName() + "\n");
		getClinicalTrialSeriesModule().dumpDICOMInfo(objIDicomStream);

		objIDicomStream.writeString("\t" + getGeneralEquipmentModule().getClass().getSimpleName() + "\n");
		getGeneralEquipmentModule().dumpDICOMInfo(objIDicomStream);
		
		objIDicomStream.writeString("\t" + getEnhancedGeneralEquipmentModule().getClass().getSimpleName() + "\n");
		getEnhancedGeneralEquipmentModule().dumpDICOMInfo(objIDicomStream);

		objIDicomStream.writeString("\t" + getSRDocumentGeneralModule().getClass().getSimpleName() + "\n");
		getSRDocumentGeneralModule().dumpDICOMInfo(objIDicomStream);

		objIDicomStream.writeString("\t" + getSRDocumentContentModule().getClass().getSimpleName() + "\n");
		getSRDocumentContentModule().dumpDICOMInfo(objIDicomStream);

		objIDicomStream.writeString("\t" + getSOPCommonModule().getClass().getSimpleName() + "\n");
		getSOPCommonModule().dumpDICOMInfo(objIDicomStream);
	}

	/**
	 * Checks whether the Module is present in the IOD or not.
	 * @param strModuleName String value of module name 
	 * @return boolean - true if the module is present in the IOD, else false is returned.
	 */
	public boolean isModulePresent(String strModuleName)
	{
		if(!super.isModulePresent(strModuleName))
		{
			if(strModuleName == null || strModuleName.equals(""))
				return false;
			if(strModuleName.equalsIgnoreCase(EnumModuleNames.PATIENT_MODULE.getValue()) && isModulePresent(PatientModule.objSingleCollection))
				return true;
			else if(strModuleName.equalsIgnoreCase(EnumModuleNames.GENERAL_STUDY_MODULE.getValue()) && isModulePresent(GeneralStudyModule.objSingleCollection))
				return true;
			else if(strModuleName.equalsIgnoreCase(EnumModuleNames.PATIENT_STUDY_MODULE.getValue()) && isModulePresent(PatientStudyModule.objSingleCollection))
				return true;
			else if(strModuleName.equalsIgnoreCase(EnumModuleNames.SR_DOCUMENT_SERIES_MODULE.getValue()) && isModulePresent(SRDocumentSeriesModule.objSingleCollection))
				return true;
			else if(strModuleName.equalsIgnoreCase(EnumModuleNames.CLINICAL_TRIAL_SERIES_MODULE.getValue()) && isModulePresent(ClinicalTrialSeriesModule.objSingleCollection))
				return true;
			else if(strModuleName.equalsIgnoreCase(EnumModuleNames.GENERAL_EQUIPMENT_MODULE.getValue()) && isModulePresent(GeneralEquipmentModule.objSingleCollection))
				return true;
			else if(strModuleName.equalsIgnoreCase(EnumModuleNames.ENHANCED_GENERAL_EQUIPMENT_MODULE.getValue()) && isModulePresent(EnhancedGeneralEquipmentModule.objSingleCollection))
				return true;
			else if(strModuleName.equalsIgnoreCase(EnumModuleNames.SR_DOCUMENT_CONTENT_MODULE.getValue()) && isModulePresent(SRDocumentContentModule.objSingleCollection))
				return true;
			else if(strModuleName.equalsIgnoreCase(EnumModuleNames.SR_DOCUMENT_GENERAL_MODULE.getValue()) && isModulePresent(SRDocumentGeneralModule.objSingleCollection))
				return true;
			else if(strModuleName.equalsIgnoreCase(EnumModuleNames.SOP_COMMON_MODULE.getValue()) && isModulePresent(SOPCommonModule.objSingleCollection))
				return true;
			else if(strModuleName.equalsIgnoreCase(EnumModuleNames.SYNCHRONIZATION_MODULE.getValue()) && isModulePresent(SynchronizationModule.objSingleCollection))
				return true;
			else
			{
				if(DicomConfig.createInstance().isLoggingOn())
				{
					DicomLogger objDicomLogger = DicomLogger.getLogger();
					objDicomLogger.log(this.getClass().getName() + " : " +ResourceBundleWrapper.getValue("status","ModuleNotPresent",new Locale(DicomConfig.createInstance().getLocale())) + strModuleName);
				}
				return false;
			}
		}
		return true;
	}
}
