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

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.IAttributeItem;
import cdac.medinfo.sdk.hl7282.utils.ISegmentMap;

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

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

	/**
	 * Provides java way of parsing xml file and populating dictionary.
	 * @param objSegmentMap object of Segment Map. 
	 */
	@SuppressWarnings("unchecked")
	boolean populate(String segmentName, ISegmentMap objSegmentMap) throws InvalidDictionaryException
	{
		String strSegmentName = null;
		int intSequence = 0;
		int iMinLength = 0;
		int iMaxLength = 0;
		String strCLength = null;
		String strDT = null;
		boolean bOptional = true;
		boolean bRepeatable = false;
		int intOccurrence = 1;
		int[] intTable = null;
		int intID = 0;
		String strName = null;
		IAttributeItem objAttributeItem = 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 segment 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(SegmentXmlNodes.valueOf(event.asStartElement().getName().getLocalPart()))
					{
					case Segment:
						iterator = event.asStartElement().getAttributes();
						while(iterator.hasNext())
						{
							Attribute attr = iterator.next();
							strSegmentName = attr.getValue();
							if(strSegmentName.equalsIgnoreCase(segmentName))
							{
								//Boolean flag becomes true, if coming Segment is our required segment.
								bflag = true;
							}
						}
						break;
					case Item:
						if(bflag)
						{
							objAttributeItem = new AttributeItem();
						}
						break;
					case ID:
						if(bflag)
						{
							if(reader.hasNext())
							{
								event = reader.nextEvent();
								String strItemID = event.asCharacters().getData();
								intID = Integer.parseInt(strItemID);
							}
						}
						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 Repeatable:
						if(bflag)
						{
							if(reader.hasNext())
							{
								event = reader.nextEvent(); 
								String strRepeat = event.asCharacters().getData();
								if(strRepeat.equalsIgnoreCase("Y"))
									bRepeatable = true;
								else 
									bRepeatable = false;
							}
						}
						break;
					case Occurrence:
						if(bflag)
						{
							if(reader.hasNext())
							{
								event = reader.nextEvent();
								String strOccurrence = event.asCharacters().getData();
								intOccurrence = Integer.parseInt(strOccurrence);
							}
						}
						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(SegmentXmlNodes.Item.getValue()))
					{
						//Data to be add in DataDictionary, if and only if, coming Segment is our required segment. 
						if(bflag)
						{
							objAttributeItem = new AttributeItem(strName,intID, intSequence, iMinLength,iMaxLength,strCLength, strDT);
							objAttributeItem.setTableNo(intTable);
							objAttributeItem.setRepeatable(bRepeatable);
							objAttributeItem.setOccurrence(intOccurrence);
							objAttributeItem.setOptional(bOptional);
							objSegmentMap.addAttributeItem(objAttributeItem);
							objAttributeItem = null;
							strName = null;
							intID = 0;
							intSequence = 0;
							iMinLength = 0; 
							iMaxLength = 0;
							strCLength = null;
							strDT = null;
							intTable = null;
							bRepeatable = false;
							intOccurrence = 1;
							bOptional = true;
						}
					}
					else if (event.asEndElement().getName().getLocalPart().equalsIgnoreCase(SegmentXmlNodes.Segment.getValue()))
					{
						//Boolean flag, to check coming Segment is required or not, if the Segment is not required segment
						//then flag is true and that means our required segment is already populated and not need to read further.
						if(bflag)
							return bflag;
					}
					else if (event.asEndElement().getName().getLocalPart().equalsIgnoreCase(SegmentXmlNodes.SegmentMapDictionary.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;
	}

	/**
	 * 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();
	}
}
