/*******************************************************************************
 *  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 java.io.ByteArrayOutputStream;
import java.io.IOException;

import cdac.medinfo.sdk.dcm30_04.commoninterface.IDataElement;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IDicomStream;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IDictionaryReader;
import cdac.medinfo.sdk.dcm30_04.commoninterface.ITransferSyntax;
import cdac.medinfo.sdk.dcm30_04.dicomstreams.DicomBufferStream;
import cdac.medinfo.sdk.dcm30_04.dictionaryreaderwriters.DictionaryReader;
import cdac.medinfo.sdk.dcm30_04.exceptions.InvalidDataElementException;
import cdac.medinfo.sdk.dcm30_04.exceptions.InvalidDictionaryException;
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.StandardMethods;

/**
 * This class contains the Image Element i.e. Data element representing pixel data.
 * This class is written for memory efficiency. It is child of DataElement with an additional functionality
 * of getting bytes of image data. The getBytes function returns the byte array of iNumberOfBytes to the user.
 */
public class ImageElement extends DataElement  
{
	
	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	IDataElement objIDataElement = null;

	byte[] arrDataElementByteHeader = null;
	boolean flag = false;

	/**
	 * Creates Image Element with specified Transfer syntax and OBImageObject Dicom Data.
	 * @param objITransferSyntax value of Transfer Syntax.
	 * @param objOBImageObject populated object of OBImageObject.
	 */
	public ImageElement(ITransferSyntax objITransferSyntax , OBImageObject objOBImageObject) throws InvalidDataElementException
	{
		try
		{
			if(objIDictionaryReader == null )
			{
				objIDictionaryReader = DictionaryReader.createInstance();
				objIDictionaryReader.populate();
			}
			if(objITransferSyntax.getVRTransferSyntax() == DicomConstants.DCM_VR_IMPLICIT)
				objIDataElement = new ImplicitDE(0x07FE0, 0x0010, objOBImageObject, objITransferSyntax,objIDictionaryReader);
			else
				objIDataElement = new ExplicitDE(0x07FE0, 0x0010,DicomConstants.DCM_DT_OB, objOBImageObject, objITransferSyntax,objIDictionaryReader);

			this.objITag = objIDataElement.getTag();
			this.objIDicomValue = objIDataElement.getDicomValue();
			this.objITransferSyntax = objIDataElement.getTransferSyntax();
			this.iVM = objIDataElement.getValueMultiplicity();
		}
		catch(InvalidDictionaryException ide)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger.getLogger().log(ide.getMessage());
			}
			throw new InvalidDataElementException(ide.getMessage(),ide);
		}
	}

	/**
	 * Creates Image Element with specified Transfer syntax and OWImageObject Dicom Data.
	 * @param objITransferSyntax value of Transfer Syntax.
	 * @param objOWImageObject populated object of OWImageObject.
	 */
	public ImageElement(ITransferSyntax objITransferSyntax, OWImageObject objOWImageObject) throws InvalidDataElementException
	{
		try
		{
			if(objIDictionaryReader == null )
			{
				objIDictionaryReader = DictionaryReader.createInstance();
				objIDictionaryReader.populate();
			}
			if(objITransferSyntax.getVRTransferSyntax() == DicomConstants.DCM_VR_EXPLICIT)
				objIDataElement = new ExplicitDE(0x07FE0, 0x0010,DicomConstants.DCM_DT_OW, objOWImageObject, objITransferSyntax,objIDictionaryReader);
			else
				objIDataElement = new ImplicitDE(0x07FE0, 0x0010, objOWImageObject, objITransferSyntax,objIDictionaryReader);

			this.objITag = objIDataElement.getTag();
			this.objIDicomValue = objIDataElement.getDicomValue();
			this.objITransferSyntax = objIDataElement.getTransferSyntax();
			this.iVM = objIDataElement.getValueMultiplicity();
		}
		catch(InvalidDictionaryException ide)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger.getLogger().log(ide.getMessage());
			}
			throw new InvalidDataElementException(ide.getMessage(),ide);
		}
	}

	/**
	 * Creates Image Element with specified Transfer syntax and OBImageObject Dicom Data.
	 * @param objITransferSyntax value of Transfer Syntax.
	 * @param objOBImageObject populated object of Dicom Data OBImageObject.
	 * @param objIDictionaryReader instance of Dictionary Reader.
	 */
	public ImageElement(ITransferSyntax objITransferSyntax, IDictionaryReader objIDictionaryReader, OBImageObject objOBImageObject)
	{
		if(objITransferSyntax.getVRTransferSyntax() == DicomConstants.DCM_VR_IMPLICIT)
			objIDataElement = new ImplicitDE(0x07FE0, 0x0010, objOBImageObject, objITransferSyntax,objIDictionaryReader);
		else
			objIDataElement = new ExplicitDE(0x07FE0, 0x0010,DicomConstants.DCM_DT_OB, objOBImageObject, objITransferSyntax,objIDictionaryReader);

		this.objITag = objIDataElement.getTag();
		this.objIDicomValue = objIDataElement.getDicomValue();
		this.objITransferSyntax = objIDataElement.getTransferSyntax();
		this.iVM = objIDataElement.getValueMultiplicity();
	}

	/**
	 * Creates Image Element with specified Transfer syntax and OWImageObject Dicom Data.
	 * @param objITransferSyntax value of Transfer Syntax.
	 * @param objOWImageObject populated object of Dicom Data OWImageObject.
	 * @param objIDictionaryReader instance of Dictionary Reader.
	 */
	public ImageElement(ITransferSyntax objITransferSyntax, IDictionaryReader objIDictionaryReader,OWImageObject objOWImageObject )
	{
		if(objITransferSyntax.getVRTransferSyntax() == DicomConstants.DCM_VR_EXPLICIT)
			objIDataElement = new ExplicitDE(0x07FE0, 0x0010,DicomConstants.DCM_DT_OW, objOWImageObject, objITransferSyntax,objIDictionaryReader);
		else
			objIDataElement = new ImplicitDE(0x07FE0, 0x0010, objOWImageObject, objITransferSyntax,objIDictionaryReader);

		this.objITag = objIDataElement.getTag();
		this.objIDicomValue = objIDataElement.getDicomValue();
		this.objITransferSyntax = objIDataElement.getTransferSyntax();
		this.iVM = objIDataElement.getValueMultiplicity();
	}

	/**
	 * This constructor initializes Image Element object.
	 * @param objIDataElement The object of data element representing image element.
	 */
	public ImageElement(IDataElement objIDataElement) 
	{
		this.objIDataElement = objIDataElement;
	}

	/**
	 * The implementation of this method parses the image element.
	 * @param objIDicomStream stream from which the DataElement is to be parsed and populated
	 */
	public int parse(IDicomStream objIDicomStream) throws InvalidDataElementException, IOException
	{
		objIDataElement.parse(objIDicomStream);
		return 1;
	}

	/**
	 * The implementation of this method serializes the image element.
	 * @param objIDicomStream stream to which the DataElement is to be serialized.
	 */
	public int serialize(IDicomStream objIDicomStream) throws InvalidDataElementException, IOException
	{
		objIDataElement.serialize(objIDicomStream);
		return 1;
	}

	/**
	 * The implementation of this method gets the length of image element.
	 * @return int - integer value of length of data element.
	 */
	public int getDataElementLength()
	{
		return objIDataElement.getDataElementLength();
	}

	/**
	 * The implementation of this method gets the iNumberOfBytes of image element and returns a byte array.
	 * @param iNumberOfBytes  Number of bytes of image data required.
	 * @return byte[] byte array of iNumberOfBytes
	 * @throws IOException if IO operation fails
	 */
	public byte[] getBytes(int iNumberOfBytes) throws IOException
	{
		byte arrByte[] = new byte[iNumberOfBytes];
		int arrByteIndex = 0;
		if(flag == false)								
		{
			arrDataElementByteHeader = getDataElementHeader();
			//flag is set to true after header is read once. So that each time get bytes is called the header is not read.
			flag = true;
		}
		if(arrDataElementByteHeader != null)
		{
			//if length of data element header is equal to number of bytes required then return it.
			if(arrDataElementByteHeader.length == iNumberOfBytes)
			{
				System.arraycopy(arrDataElementByteHeader, 0, arrByte, 0, iNumberOfBytes);
				arrDataElementByteHeader = null;
				return arrByte;
			}
			//if length of data element header is greater number of bytes required then copy iNumberOfBytes in arrByte
			//initialize arrDataElementByteHeader with remaining bytes and return arrByte.
			else if(arrDataElementByteHeader.length > iNumberOfBytes)
			{
				System.arraycopy(arrDataElementByteHeader, 0, arrByte, 0, iNumberOfBytes);
				byte[] tempByte = new byte[arrDataElementByteHeader.length-iNumberOfBytes];
				System.arraycopy(arrDataElementByteHeader, iNumberOfBytes, tempByte, 0, tempByte.length);
				arrDataElementByteHeader = tempByte;
				return arrByte;
			}
			//if length of data element header is smaller than number of bytes required then copy arrDataElementByteHeader in arrByte
			//read the remaining bytes of image data
			else
			{
				System.arraycopy(arrDataElementByteHeader, 0, arrByte, 0, arrDataElementByteHeader.length);
				arrByteIndex = arrByteIndex + arrDataElementByteHeader.length;

				int iLeftBytes = iNumberOfBytes- arrDataElementByteHeader.length;
				if(objIDataElement.getTag().equals(new Tag(0x7fe0 , 0x0010)))
				{
					if (objIDataElement.getDicomValue() instanceof OBImageObject)
					{
						OBImageObject objOBImageObject = (OBImageObject)objIDataElement.getDicomValue();
						byte[] arrImageByte = objOBImageObject.getBytes(iLeftBytes);
						System.arraycopy(arrImageByte, 0, arrByte, arrByteIndex, arrImageByte.length);
						arrByteIndex = arrByteIndex+arrImageByte.length;
						arrDataElementByteHeader = null;
						if(arrByteIndex != iNumberOfBytes)
						{
							byte[] arrByteLeft = new byte[arrByteIndex];
							System.arraycopy(arrByte, 0, arrByteLeft, 0, arrByteLeft.length);
							return arrByteLeft;
						}
						return arrByte;
					}
					else
					{
						OWImageObject objOWImageObject = (OWImageObject)objIDataElement.getDicomValue();
						byte[] arrImageByte = objOWImageObject.getBytes(iLeftBytes);
						System.arraycopy(arrImageByte, 0, arrByte, arrDataElementByteHeader.length, arrImageByte.length);
						arrByteIndex = arrByteIndex+arrImageByte.length;
						arrDataElementByteHeader = null;
						if(arrByteIndex != iNumberOfBytes)
						{
							byte[] arrByteLeft = new byte[arrByteIndex];
							System.arraycopy(arrByte, 0, arrByteLeft, 0, arrByteLeft.length);
							return arrByteLeft;
						}
						return arrByte;
					}
				}
			}
		}
		//if arrDataElementByteHeader is null i.e all its byte are read then read data from image element.
		else
		{
			if(objIDataElement.getTag().equals(new Tag(0x7fe0 , 0x0010)))
			{
				byte[] arrImageByte = null;
				if (objIDataElement.getDicomValue() instanceof OBImageObject)
				{
					OBImageObject objOBImageObject = (OBImageObject)objIDataElement.getDicomValue();
					arrImageByte = objOBImageObject.getBytes(iNumberOfBytes);

				}
				else
				{
					OWImageObject objOWImageObject = (OWImageObject)objIDataElement.getDicomValue();
					arrImageByte = objOWImageObject.getBytes(iNumberOfBytes);
				}
				return arrImageByte;

			}
		}
		return null;
	}

	/**
	 * This method gives information if OB image Object data is available.
	 * @return boolean - true if OB image Object data is available
	 * 					 false if OB image Object data is not available
	 * @throws IOException if IO operation fails
	 */ 
	public boolean isAvailable() throws IOException
	{
		if (arrDataElementByteHeader != null)
			return true;
		if(objIDataElement.getTag().equals(new Tag(0x7fe0 , 0x0010)))
		{
			if (objIDataElement.getDicomValue() instanceof OBImageObject)
			{
				OBImageObject objOBImageObject = (OBImageObject)objIDataElement.getDicomValue();
				return objOBImageObject.isAvailable();
			}
			else
			{
				OWImageObject objOWImageObject = (OWImageObject)objIDataElement.getDicomValue();
				return objOWImageObject.isAvailable();
			}
		}
		return false;
	}

	//This function serialize the header into a byte array.
	private byte[] getDataElementHeader() throws IOException
	{
		DicomBufferStream objDicomBufferStream = new DicomBufferStream();
		ByteArrayOutputStream objByteArrayOutputStream = new ByteArrayOutputStream();
		objDicomBufferStream.setOutputStream(objByteArrayOutputStream);
		objDicomBufferStream.setEndianNess(objIDataElement.getTransferSyntax().getEndianNess());

		short shGroupNo = (short)objIDataElement.getTag().getGroupNumber();
		short shElementNO =(short)objIDataElement.getTag().getElementNumber();

		//Write the Group number and Group element
		objDicomBufferStream.writeShort(shGroupNo);
		objDicomBufferStream.writeShort(shElementNO);

		//Write the VR type. 
		if(objIDataElement.getTransferSyntax().getVRTransferSyntax() == DicomConstants.DCM_VR_EXPLICIT)
		{
			if (objIDataElement.getDicomValue() instanceof OBImageObject)
			{
				objDicomBufferStream.writeString(StandardMethods.getStrVRtype(DicomConstants.DCM_DT_OB));
			}
			else
				objDicomBufferStream.writeString(StandardMethods.getStrVRtype(DicomConstants.DCM_DT_OW));

			byte zeroValue = 0;
			objDicomBufferStream.writeByte(zeroValue);
			objDicomBufferStream.writeByte(zeroValue);
			objDicomBufferStream.writeInt(objIDataElement.getValueLength());
		}
		else
		{
			if((getValueLength() != DicomConstants.DCM_UNDEFINED_LENGTH) && ((getValueLength() % 2) != 0))
				objDicomBufferStream.writeInt(getValueLength() + 1);
			else
				objDicomBufferStream.writeInt(objIDataElement.getValueLength());
		}

		//Write the 4 bytes for value length
		return objDicomBufferStream.toByteArray();
	}


	/**
	 * This function validates the Image Element.
	 * @throws InvalidDataElementException Signals if Data Element Validation Fails.
	 */
	public boolean validate() throws InvalidDataElementException
	{
		return true;
	}

	@SuppressWarnings("unchecked")
	public ISingleCollection<byte[]> getValue()
	{
		if(objIDataElement != null)
		{
			return (ISingleCollection<byte[]>)objIDataElement.getValue();
		}
		return null;
	}

	/**
	 * This function disposes the Image Element.
	 * @throws IOException Signals if an IO Exception occurs.
	 */
	public void dispose() throws IOException
	{
		if (objIDataElement.getDicomValue() instanceof OBImageObject)
		{
			OBImageObject objOBImageObject = (OBImageObject)objIDataElement.getDicomValue();
			objOBImageObject.dispose();
		}
		else
		{
			OWImageObject objOWImageObject = (OWImageObject)objIDataElement.getDicomValue();
			objOWImageObject.dispose();
		}
	}
}
