/*******************************************************************************
 *  Copyright 2017 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.hl7282.baselibs.datatypefactory;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Iterator;

import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.XMLEvent;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import cdac.medinfo.sdk.hl7282.exceptions.InvalidDictionaryException;
import cdac.medinfo.sdk.hl7282.utils.HL7Config;
import cdac.medinfo.sdk.hl7282.utils.HL7Logger;
import cdac.medinfo.sdk.hl7282.utils.IComponentItem;
import cdac.medinfo.sdk.hl7282.utils.IDataTypeMap;

/**
 * XML Handler class provides java dependent implementation of XML File parsing mechanism.
 */
public class DataTypeXmlHandler 
{
	String strXmlFile = null;
	//Document document = null;
	InputStream objFileInputStream = null;

	/**
	 * This constructor accepts File Stream.
	 * @param objFileInputStream File Input Stream.
	 */
	public DataTypeXmlHandler(InputStream objFileInputStream)
	{
		this.objFileInputStream = objFileInputStream;
	}

	/**
	 * The method provides java way of parsing xml file and populating dictionary.
	 * @param objDataTypeMap object of DataType Map. 
	 */
	@SuppressWarnings("unchecked")
	boolean populate(String DataTypeName, IDataTypeMap objDataTypeMap) throws InvalidDictionaryException
	{
		String strDataTypeName = null;
		int intSequence = 0;
		int iMinLength = 0;
		int iMaxLength = 0;
		String strCLength = null;
		String strDT = null;
		boolean bOptional = false;
		int[] intTable = null;
		String strName = null;
		IComponentItem objComponentItem = null;

		try
		{
			//Creates instance of XMLEventReader for xml file
			XMLInputFactory inputFactory = XMLInputFactory.newInstance();

			if(objFileInputStream == null)
				objFileInputStream = new FileInputStream(strXmlFile);

			XMLEventReader reader = 
				inputFactory.createXMLEventReader(objFileInputStream);

			//Boolean flag, is to check weather required DataType is populated or not.
			boolean bflag = false;

			//Traverses through the nodes of xml file using event based mechanism of StAX parser
			while(reader.hasNext())
			{
				XMLEvent event = reader.nextEvent(); 
				Iterator<Attribute> iterator = null;
				switch(event.getEventType())
				{
				//event type START_ELEMENT defines the start tag of the xml node in the file
				case XMLStreamConstants.START_ELEMENT:
				{
					//processes each node and retrieves the attribute or value of the node
					switch(DataTypeXmlNodes.valueOf(event.asStartElement().getName().getLocalPart()))
					{
					case DataType:
						iterator = event.asStartElement().getAttributes();
						while(iterator.hasNext())
						{
							Attribute attr = iterator.next();
							strDataTypeName = attr.getValue();
							if(strDataTypeName.equalsIgnoreCase(DataTypeName))
							{
								//Boolean flag becomes true, if coming DataType is our required DataType.
								bflag = true;
							}
						}
						break;
					case Item:
						if(bflag)
						{
							objComponentItem = new ComponentItem();
						}
						break;
					case Name:
						if(bflag)
						{
							if(reader.hasNext())
							{
								event = reader.nextEvent(); 
								strName = event.asCharacters().getData();
							}
						}
						break;
					case Sequence:
						if(bflag)
						{
							if(reader.hasNext())
							{
								event = reader.nextEvent(); 
								String strSequence = event.asCharacters().getData();
								intSequence = Integer.parseInt(strSequence);
							}
						}
						break;
					case MinLength:
						if(bflag)
						{
							if(reader.hasNext())
							{
								event = reader.nextEvent(); 
								String strLength = event.asCharacters().getData();
								iMinLength = Integer.parseInt(strLength);
							}
						}
						break;
					case MaxLength:
						if(bflag)
						{
							if(reader.hasNext())
							{
								event = reader.nextEvent(); 
								String strLength = event.asCharacters().getData();
								iMaxLength = Integer.parseInt(strLength);
							}
						}
						break;
					case CLength:
						if(bflag)
						{
							if(reader.hasNext())
							{
								event = reader.nextEvent(); 
								strCLength = event.asCharacters().getData();
							}
						}
						break;
					case DT:
						if(bflag)
						{
							if(reader.hasNext())
							{
								event = reader.nextEvent(); 
								strDT = event.asCharacters().getData();
							}
						}
						break;
					case Table:
						if(bflag)
						{
							if(reader.hasNext())
							{
								event = reader.nextEvent(); 
								String strTable = event.asCharacters().getData();
								String [] arrTable = strTable.split("_");
								intTable = new int[arrTable.length];
								for(int i=0; i < arrTable.length ; i++)
								{
									intTable[i] = Integer.parseInt(arrTable[i]);
								}
							}
						}
						break;
					case Optional:
						if(bflag)
						{
							if(reader.hasNext())
							{
								event = reader.nextEvent(); 
								String strOptional = event.asCharacters().getData();
								if(strOptional.equalsIgnoreCase("R"))
									bOptional = false;
								else
									bOptional = true;
							}
						}
						break;
					}
				}
				break;
				//event type END_ELEMENT defines the end tag of the xml node in the file
				case XMLStreamConstants.END_ELEMENT:
				{
					if (event.asEndElement().getName().getLocalPart().equalsIgnoreCase(DataTypeXmlNodes.Item.getValue()))
					{
						//Data to be add in DataDictionary, if and only if, coming DataType is our required DataType. 
						if(bflag)
						{
							objComponentItem = new ComponentItem(strName,intSequence, iMinLength,iMaxLength,strCLength, strDT);
							objComponentItem.setOptional(bOptional);
							objComponentItem.setTableNo(intTable);
							objDataTypeMap.addComponentItem(objComponentItem);
							objComponentItem = null;
							strName = null;
							intSequence = 0;
							iMinLength = 0; 
							iMaxLength = 0;
							strCLength = null;
							strDT = null;
							intTable = null;
							bOptional = false;
						}
					}
					else if (event.asEndElement().getName().getLocalPart().equalsIgnoreCase(DataTypeXmlNodes.DataType.getValue()))
					{
						//Boolean flag, to check coming DataType is required or not, if the DataType is not required DataType
						//then flag is true and that means our required DataType is already populated and not need to read further.
						if(bflag)
							return bflag;
					}
					else if (event.asEndElement().getName().getLocalPart().equalsIgnoreCase(DataTypeXmlNodes.DataTypeMapDictionary.getValue()))
					{
						return bflag;
					}
				}
				break;
				}	
			}
		}catch(XMLStreamException xse)
		{
			if(HL7Config.createInstance().isLoggingOn())
			{
				HL7Logger.getLogger().log(xse.getMessage());
			}
			throw new InvalidDictionaryException(xse);
		}
		catch(FileNotFoundException fnfe)
		{
			if(HL7Config.createInstance().isLoggingOn())
			{
				HL7Logger.getLogger().log(fnfe.getMessage());
			}
			throw new InvalidDictionaryException(fnfe);
		}
		
		return false;
	}

	/**
	 * This method provides the value of the Node passed to it.
	 * @param attrNode object of Node.
	 * @return String - string value of a node.
	 */
	String getValueAttribute(Node attrNode)
	{
		NamedNodeMap objNamedNodeMap = attrNode.getAttributes();
		Node objNode = objNamedNodeMap.getNamedItem("value");
		return objNode.getNodeValue();
	}
}
