/*******************************************************************************
 *  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.enums.EnumObserverType;
import cdac.medinfo.sdk.dcm30_04.exceptions.ConditionFailedException;
import cdac.medinfo.sdk.dcm30_04.exceptions.InvalidMacroException;
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;

/**
 * This class describes a Macro which defines the Attributes that identify a person or a device participating as an observer for the 
 * context of an SR Instance.This macro contains content equivalent to TID 1002.
 * @author saloni
 *
 */
public class IdentifiedPersonorDeviceMacro extends Macro   
{
	

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

	/**
	 * This constructor constructs a Macro with specified DataSet.
	 * @param objDataSet Collection of DataElements 
	 */
	public IdentifiedPersonorDeviceMacro(IDataSet objDataSet)
	{
		super(objDataSet);
	}

	/**
	 * This constructor constructs a Macro with specified DataSet and DictionaryReader
	 * @param objDataSet specifies the DataSet
	 * @param objDictionaryReader specifies the DICOM Dictionary reader to be used 
	 */
	public IdentifiedPersonorDeviceMacro(IDataSet objDataSet,IDictionaryReader objDictionaryReader)
	{
		super(objDataSet,objDictionaryReader);
	}

	/**
	 * This constructor constructs a Macro with the specified Item
	 * @param objItem specifies instance of Item class
	 */
	public IdentifiedPersonorDeviceMacro(IItem objItem)
	{
		super(objItem);
	}

	/**
	 * This constructor constructs a Macro with the specified Item and DictionaryReader
	 * @param objItem specifies instance of Item class
	 * @param objDictionaryReader specifies the DICOM Dictionary reader to be used 
	 */
	public IdentifiedPersonorDeviceMacro(IItem objItem,IDictionaryReader objDictionaryReader)
	{
		super(objItem, objDictionaryReader);
	}

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

	/**
	 * Validates all the attributes in IdentifiedPersonorDeviceMacro that are present in the DataSet
	 * @param objIDataSet collection of DataElements
	 * @return boolean - Success -true, Failure - false
	 * @throws InvalidMacroException throws InvalidMacroException If Mandatory or Conditional element fails.
	 */
	public static boolean validate(IDataSet objIDataSet) throws InvalidMacroException
	{
		try
		{ 

			//validate condition here
			if(!objIDataSet.isPresent(0x0040,0xA084))
				throw new MandatoryMissingException("0040,A084");
			
			if(objIDataSet.getDataForTag(0x0040, 0xA084).getValue().equals(EnumObserverType.Person)){
				if(!objIDataSet.isPresent(0x0040,0xA123))
					throw new ConditionFailedException("0040,A123");
				if(!objIDataSet.isPresent(0x0040,0x1101))
					throw new ConditionFailedException("0040,1101");
				
			}
			if(objIDataSet.getDataForTag(0x0040, 0xA084).getValue().equals(EnumObserverType.Device)){
				if(!objIDataSet.isPresent(0x0008,0x1010))
					throw new ConditionFailedException("0008,1010");
				if(!objIDataSet.isPresent(0x0018,0x1002))
					throw new ConditionFailedException("0018,1002");
				if(!objIDataSet.isPresent(0x0008,0x0070))
					throw new ConditionFailedException("0008,0070");
				if(!objIDataSet.isPresent(0x0008,0x1090))
					throw new ConditionFailedException("0008,1090");
			}
			if(!objIDataSet.isPresent(0x0008,0x0080))
				throw new MandatoryMissingException("0008,0080");
			if(!objIDataSet.isPresent(0x0008,0x0082))
				throw new MandatoryMissingException("0008,0082");
		}
		catch( ConditionFailedException ce)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger.getLogger().log(ce.getMessage());
			}
			throw new InvalidMacroException( IdentifiedPersonorDeviceMacro.class.getSimpleName() ,ce); 
		}
		catch( MandatoryMissingException me)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger.getLogger().log(me.getMessage());
			}
			throw new InvalidMacroException(IdentifiedPersonorDeviceMacro.class.getSimpleName() ,me);
		}
		return true;
	}

	/**
	 * Validates all the attributes in IdentifiedPersonorDeviceMacro that are present in the DataSet
	 * @param objIItem collection of DataElements in a sequence
	 * @return boolean - Success -true, Failure - false
	 * @throws InvalidMacroException throws InvalidMacroException If Mandatory or Conditional element fails.
	 */
	public static boolean validate(IItem objIItem) throws InvalidMacroException
	{
		try
		{  
			//validate condition here
			if(!objIItem.contains(0x0040,0xA084))
				throw new MandatoryMissingException("0040,A084");
			if(!objIItem.contains(0x0046,0x0080))
				throw new MandatoryMissingException("0046,0080)");
		}
		catch( ConditionFailedException ce)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger.getLogger().log(ce.getMessage());
			}
			throw new InvalidMacroException(IdentifiedPersonorDeviceMacro.class.getSimpleName(),ce); 
		}
		catch( MandatoryMissingException me)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger.getLogger().log(me.getMessage());
			}
			throw new InvalidMacroException(IdentifiedPersonorDeviceMacro.class.getSimpleName(),me);
		}
		return true;
	}
	
	/**
	 * Sets type of Observer.
	 * Defined Terms:
	 * 1) PSN.
	 * 2) DEV.
	 * @param enumObserverType enum value of Observer Type.
	 */
	public void setObserverType(EnumObserverType enumObserverType)
	{
		/* Accept the Observer 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(0x0040,0xA084, enumObserverType.getValue(), objIDictionaryReader);
		else
			objIDataElement = new ExplicitDE(0x0040,0xA084,DicomConstants.DCM_DT_CS, enumObserverType.getValue());

		addDataElement(objIDataElement);


	}

	/**
	 * Return type of Observer. 
	 * @return String - value of Observer Type.
	 */
	public String getObserverType()
	{
		Object objValue = getValue(0x0040,0xA084);
		if(objValue != null)
			return objValue.toString();
		return null;
	}

	/**
	 * Sets Person Name.
	 * Name of the person observer for this document Instance.
	 * @param strPersonName String Person Name.
	 */	
	public void setPersonName(String strPersonName)
	{
		/*Accept Person Name in String format of type PN.
		 * Read the Transfer Syntax and check to create ImplicitDE or ExplicitDE .
		 * Set the iGroupNumber and iElementNumber to ImplicitDE object 
		 * Set the iVRType
		 * Set length from the element
		 * Add this element to the Hash Map
		 */
		IDataElement objIDataElement = null;
		if(objITransferSyntax.getVRTransferSyntax() == DicomConstants.DCM_VR_IMPLICIT)
			objIDataElement = new ImplicitDE(0x0040,0xA123,strPersonName,objIDictionaryReader);
		else
			objIDataElement = new ExplicitDE(0x0040,0xA123, DicomConstants.DCM_DT_PN,strPersonName);
		addDataElement(objIDataElement);
	}

	/**
	 * Retrieves Person Name.
	 * Name of the person observer for this document Instance.
	 * @return String - Name of the Person.
	 */
	public String getPersonName()
	{
		Object objValue = getValue(0x0040,0xA123);
		if(objValue != null)
			return objValue.toString();
		return null;
	}
	
	/**
	 * Retrieves pre-initialized object of Person Identification Code 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 PersonIdentificationCodeSequence - instance of PersonIdentificationCodeSequence. 
	 */
	public PersonIdentificationCodeSequence getPersonIdentificationCodeSequence()
	{
		PersonIdentificationCodeSequence objPersonIdentificationCodeSequence = null;
		IDataElement objIDataElement =  getDataElement(0x0040, 0x1101);
		if(objIDataElement != null)
		{
			IDicomValue objIDicomValue = objIDataElement.getDicomValue();
			if(objIDicomValue != null)
				objPersonIdentificationCodeSequence = (PersonIdentificationCodeSequence)objIDicomValue;
		}
		else
		{
			DicomV3Factory objDicomV3Factory = DicomV3Factory.createInstance();
			int iVRTransferSyntax = objITransferSyntax.getVRTransferSyntax();
			objIDataElement = null;
			objPersonIdentificationCodeSequence = (PersonIdentificationCodeSequence)objDicomV3Factory.createSequence(0x0040, 0x1101, objITransferSyntax, objIDictionaryReader);

			if(iVRTransferSyntax == DicomConstants.DCM_VR_IMPLICIT)
				objIDataElement = new ImplicitDE(0x0040, 0x1101, objPersonIdentificationCodeSequence.getValue(),objIDictionaryReader);
			else
				objIDataElement = new ExplicitDE(0x0040, 0x1101, DicomConstants.DCM_DT_SQ, objPersonIdentificationCodeSequence.getValue());
			objIDataElement.setTransferSyntax(objITransferSyntax);
			if(objIDataElement != null)
				addDataElement(objIDataElement);
		}
		return objPersonIdentificationCodeSequence;
	}
	
	/**
	 * Sets the Station Name.
	 * Name of the device observer for this document instance.
	 * @param strStationName - value of Station Name
	 */
	public void setStationName(String strStationName)
	{
		/*Accept the Station Name in String format of type SH.
		 * 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(0x0008, 0x1010, strStationName,objIDictionaryReader);
		else
			objIDataElement = new ExplicitDE(0x0008, 0x1010,DicomConstants.DCM_DT_SH, strStationName);

		addDataElement(objIDataElement);
	}

	/**
	 * Retrieves Station Name.
	 * Name of the device observer for this document instance.
	 * @return String - value of Station Name.
	 */
	public String getStationName()
	{
		Object objValue = getValue(0x0008, 0x1010);
		if(objValue != null)
			return objValue.toString();
		return null;
	}
	
	/**
	 * Sets a Device UID.
	 * Unique identifier of device observer.
	 * @param strDeviceUID String value of Device UID.
	 */
	public void setDeviceUID(String strDeviceUID)
	{
		/*Accept the Device 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(0x0018, 0x1002, strDeviceUID,objIDictionaryReader);
		else
			objIDataElement = new ExplicitDE(0x0018, 0x1002,DicomConstants.DCM_DT_UI, strDeviceUID);

		addDataElement(objIDataElement);
	}

	/**
	 * Retrieves a Device UID.
	 * Unique identifier of device observer.
	 * @return String - value of Device UID.
	 */
	public String getDeviceUID()
	{
		Object objValue = getValue(0x0018, 0x1002);
		if(objValue != null)
			return objValue.toString();
		return null;
	}
	
	/**
	 * Sets Manufacturer.
	 * @param strManufacturer String value of Manufacturer.
	 */
	public void setManufacturer(String strManufacturer)
	{
		/* Accept the Manufacturer in String format of type LO.
		 * 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(0x0008,0x0070, strManufacturer,objIDictionaryReader);
		else
			objIDataElement = new ExplicitDE(0x0008,0x0070,DicomConstants.DCM_DT_LO, strManufacturer);

		addDataElement(objIDataElement);
	}

	/**
	 * Return Manufacturer.
	 * @return String - value of Manufacturer.
	 */
	public String getManufacturer()
	{
		Object objValue = getValue(0x0008,0x0070);
		if(objValue != null)
			return objValue.toString();
		return null;
	}
	
	/**
	 * Sets Manufacturer's model name.
	 * Model Name of the device observer.
	 * @param strManufacturersModelName String value of Manufacturers Model Name .
	 */
	public void setManufacturersModelName(String strManufacturersModelName)
	{
		/*Accept the ManufacturersModelName in String format of type LO.
		 * 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(0x0008,0x1090, strManufacturersModelName, objIDictionaryReader);
		else
			objIDataElement = new ExplicitDE(0x0008,0x1090,DicomConstants.DCM_DT_LO, strManufacturersModelName);

		addDataElement(objIDataElement);
	}
	/**
	 * Retrieves Manufacturer's model name.
	 * Model Name of the device observer.
	 * @return String - value of Manufacturers Model Name.
	 */
	public String getManufacturersModelName()
	{
		Object objValue = getValue(0x0008,0x1090);
		if(objValue != null)
			return objValue.toString();
		return null;
	}
	
	/**
	 * Sets Institution Name.
	 * @param strInstitutionName String value of Institution Name .
	 */
	public void setInstitutionName(String strInstitutionName)
	{
		/*Accept the InstitutionName in String format of type LO.
		 * 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(0x0008,0x0080, strInstitutionName, objIDictionaryReader);
		else
			objIDataElement = new ExplicitDE(0x0008,0x0080,DicomConstants.DCM_DT_LO, strInstitutionName);

		addDataElement(objIDataElement);
	}
	/**
	 * Retrieves Institution Name.
	 * @return String - value of Institution Name.
	 */
	public String getInstitutionName()
	{
		Object objValue = getValue(0x0008,0x0080);
		if(objValue != null)
			return objValue.toString();
		return null;
	}
	
	/**
	 * Retrieves pre-initialized object of Institution Code 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 InstitutionCodeSequence - instance of InstitutionCodeSequence. 
	 */
	public InstitutionCodeSequence getInstitutionCodeSequence()
	{
		InstitutionCodeSequence objInstitutionCodeSequence = null;
		IDataElement objIDataElement =  getDataElement(0x0008, 0x0082); 
		if(objIDataElement != null)
		{
			IDicomValue objIDicomValue = objIDataElement.getDicomValue();
			if(objIDicomValue != null)
				objInstitutionCodeSequence = (InstitutionCodeSequence)objIDicomValue;
		}
		else
		{
			DicomV3Factory objDicomV3Factory = DicomV3Factory.createInstance();
			int iVRTransferSyntax = objITransferSyntax.getVRTransferSyntax();
			objIDataElement = null;
			objInstitutionCodeSequence = (InstitutionCodeSequence)objDicomV3Factory.createSequence(0x0008, 0x0082, objITransferSyntax, objIDictionaryReader);

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

}
