package com.qa.utilities;

import java.io.File;
import java.util.Iterator;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.qa.utilities.Util;


public class ParseXML {
	private Util util =new Util();
	Document doc= null;
	NodeList nList;
	NodeList nList1;

	//Read the XML file
	public StringBuffer ReadXMLFileFromLocal(File file) {
		StringBuffer NodeNames = new StringBuffer(); 
		try {

			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			doc = dBuilder.parse(file);
		}
		catch(Exception e)
		{ e.printStackTrace();}

		NodeNames = visit(doc ,0);
		return NodeNames;
	}

	//Helper Method Update the XML file for the given Node name and new value
	public void UpdateNodeNameValue (String NodeName, String NewValue) {
		UpdateNameValue(doc,0,NodeName,NewValue);
	}
	
	//Method for Updating the XML file for the given Node name and new value
	//Method Traverses the entire XML documment to search for the nnode
	public void   UpdateNameValue(Node node, int level, String NodeName, String NewValue) {
		StringBuffer NodeNames = new StringBuffer();
		if(NodeName.equalsIgnoreCase(node.getNodeName()))
		{
			node.setTextContent(NewValue);
			try
			{       
				//Writes the new content to the XML file
				doc.getDocumentElement().normalize();
				TransformerFactory transformerFactory = TransformerFactory.newInstance();
				Transformer transformer = transformerFactory.newTransformer();
				DOMSource source = new DOMSource(doc);
				StreamResult result = new StreamResult(new File(util.getValue("employee_XML_correct_req_payload_loc")));
				transformer.setOutputProperty(OutputKeys.INDENT, "yes");
				transformer.transform(source, result);
				System.out.println("XML file updated successfully");
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
		//Traverses the entire XML document 
		NodeList list = node.getChildNodes();
		for (int i = 0; i < list.getLength(); i++) {
			Node childNode = list.item(i);
			UpdateNameValue(childNode, level + 1, NodeName, NewValue);
		}
	}
	
// Method for Traversing the XML node and returning all the node names
	public static StringBuffer  visit(Node node, int level) {
		StringBuffer NodeNames = new StringBuffer();
		System.out.println("Name: is "+node.getNodeName());
		NodeNames = NodeNames.append(node.getNodeName());	   
		System.out.println("Value: is "+node.getNodeValue());
		NodeList list = node.getChildNodes();
		for (int i = 0; i < list.getLength(); i++) {
			Node childNode = list.item(i);
			visit(childNode, level + 1);
		}
		return NodeNames;
	}

}