package test;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import XML.BoxParameters;
import XML.Icdar;



public class Test {

	//No generics
	List myEmpls;
	Document dom;


	public Test (){
		//create a list to hold the employee objects
		myEmpls = new ArrayList();
	}

	public void runExample() {

		//parse the xml file and get the dom object
		parseXmlFile();

		//get each employee element and create a Employee object
		parseDocument();

		//Iterate through the list and print the data
		printData();

	}


	private void parseXmlFile(){
		//get the factory
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

		try {

			//Using factory get an instance of document builder
			DocumentBuilder db = dbf.newDocumentBuilder();

			//parse using builder to get DOM representation of the XML file
			dom = db.parse("employees.xml");


		}catch(ParserConfigurationException pce) {
			pce.printStackTrace();
		}catch(SAXException se) {
			se.printStackTrace();
		}catch(IOException ioe) {
			ioe.printStackTrace();
		}
	}
	private void parseDocument(){
		//get the root elememt
		Element docEle = dom.getDocumentElement();

		//get a nodelist of <employee> elements
		NodeList nl = docEle.getElementsByTagName("image");
		if(nl != null && nl.getLength() > 0) {
			for(int i = 0 ; i < nl.getLength();i++) {

				//get the employee element
				Element el = (Element)nl.item(i);

				/*NodeList nl2 = el.getElementsByTagName("taggedRectangle");
		
				for(int k = 0 ; k < nl2.getLength(); k++)
				{
					Element el2 = (Element)nl2.item(k);
					String x = el2.getAttribute("x");
					String y = el2.getAttribute("y");
					String width = el2.getAttribute("width");
					String height = el2.getAttribute("height");
					String step = el2.getAttribute("offset");
					System.out.println(" Ind : " + k + " x : "  + x  + " y : "  + y  + " width : "  + width  + " height : "  + height  + " offset : "  + step);
				}*/
				
				/*Element lala = (Element)nl.item(i);
				String textVal = lala.getFirstChild().getNodeValue();
				System.out.println("Ind taggedRectangles : " + textVal);*/
			
				
				//get the Employee object
				Employee e = getEmployee(el);

				//add it to list
				myEmpls.add(e);
			}
		}
	}
	/**
	 * I take an employee element and read the values in, create
	 * an Employee object and return it
	 * @param empEl
	 * @return
	 */
	private Icdar getInfo (Element node) {

	    int width, height;
	    
	    LinkedList<BoxParameters> bParameters;
		
		String imageName = getTextValue(node,"imageName");
		
		NodeList resolution = node.getElementsByTagName("resolution");
		
		for(int i = 0 ; i < resolution.getLength(); i++)
		{
			Element elem = (Element)resolution.item(i);
			
			String x = elem.getAttribute("x");
			
			width = Integer.parseInt(x);
			
			String y = elem.getAttribute("y");
			
			height = Integer.parseInt(y);
		}
				
		NodeList boxes = node.getElementsByTagName("taggedRectangle");
		
		for(int i = 0 ; i < boxes.getLength(); i++)
		{
			BoxParameters b = new BoxParameters ();
			
			Element elem = (Element)boxes.item(i);
			
			String x = elem.getAttribute("x");
			
			b.setX (Integer.parseInt(x));
			
			String y = elem.getAttribute("y");
			
			b.setY (Integer.parseInt(y));
			
			String w = elem.getAttribute("width");
			
			b.setW (Integer.parseInt(w));
			
			String h = elem.getAttribute("height");
			
			b.setH (Integer.parseInt(h));
			
			String offset = elem.getAttribute("offset");
			
			b.setOffset (Integer.parseInt(offset));
			
			bParameters.add(b);
		}
		
		NodeList nl3 = empEl.getElementsByTagName("resolution");
		for(int k = 0 ; k < nl3.getLength(); k++)
		{
			Element el2 = (Element)nl3.item(k);
			String x = el2.getAttribute("x");
			String y = el2.getAttribute("y");
			System.out.println(" Ind : " + k + " x : "  + x  + " y : "  + y);
		}
		
		
		System.out.println("Acabei imagem : " + ImageName);
		
		//String x = empEl.getAttribute("x");
		//String y = empEl.getAttribute("y");
		
		//String resolution = getTextValue(empEl,"resolution");
		
		//System.err.println("type " + type + "x : " + x + " y : " + y + " resolution : " + resolution);

		//Create a new Employee with the value read from the xml nodes
		Employee e = new Employee(ImageName,1,1,ImageName,ImageName);

		return e;
	}
	
	private Employee getEmployee(Element empEl) {

		//for each <employee> element get text or int values of 
		//name ,id, age and name
		//String name = getTextValue(empEl,"Name");
		//int id = getIntValue(empEl,"Id");
		//int age = getIntValue(empEl,"Age");
		
		String ImageName = getTextValue(empEl,"imageName");
		
		//String type = empEl.getAttribute("type");
		
		
		NodeList nl2 = empEl.getElementsByTagName("taggedRectangle");
		
		for(int k = 0 ; k < nl2.getLength(); k++)
		{
			Element el2 = (Element)nl2.item(k);
			String x = el2.getAttribute("x");
			String y = el2.getAttribute("y");
			String width = el2.getAttribute("width");
			String height = el2.getAttribute("height");
			String step = el2.getAttribute("offset");
			System.out.println(" Ind : " + k + " x : "  + x  + " y : "  + y  + " width : "  + width  + " height : "  + height  + " offset : "  + step);
		}
		
		NodeList nl3 = empEl.getElementsByTagName("resolution");
		for(int k = 0 ; k < nl3.getLength(); k++)
		{
			Element el2 = (Element)nl3.item(k);
			String x = el2.getAttribute("x");
			String y = el2.getAttribute("y");
			System.out.println(" Ind : " + k + " x : "  + x  + " y : "  + y);
		}
		
		
		System.out.println("Acabei imagem : " + ImageName);
		
		//String x = empEl.getAttribute("x");
		//String y = empEl.getAttribute("y");
		
		//String resolution = getTextValue(empEl,"resolution");
		
		//System.err.println("type " + type + "x : " + x + " y : " + y + " resolution : " + resolution);

		//Create a new Employee with the value read from the xml nodes
		Employee e = new Employee(ImageName,1,1,ImageName,ImageName);

		return e;
	}
	/**
	 * I take a xml element and the tag name, look for the tag and get
	 * the text content 
	 * i.e for <employee><name>John</name></employee> xml snippet if
	 * the Element points to employee node and tagName is name I will return John  
	 * @param ele
	 * @param tagName
	 * @return
	 */
	private String getTextValue(Element ele, String tagName) {
		String textVal = null;
		NodeList nl = ele.getElementsByTagName(tagName);
		if(nl != null && nl.getLength() > 0) {
			Element el = (Element)nl.item(0);
			textVal = el.getFirstChild().getNodeValue();
		}

		return textVal;
	}

	/**
	 * Calls getTextValue and returns a int value
	 * @param ele
	 * @param tagName
	 * @return
	 */
	private int getIntValue(Element ele, String tagName) {
		//in production application you would catch the exception
		return Integer.parseInt(getTextValue(ele,tagName));
	}

	/**
	 * Iterate through the list and print the 
	 * content to console
	 */
	private void printData(){

		System.out.println("No of Employees '" + myEmpls.size() + "'.");

		Iterator it = myEmpls.iterator();
		while(it.hasNext()) {
			System.out.println(it.next().toString());
		}
	}


	public static void main(String[] args){
		//create an instance
		Test dpe = new Test();

		//call run example
		dpe.runExample();
	}

}

    
    
    




















/*import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.*;


import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class Test {

    public static void main (String argv []){
    try {

    	    System.out.println("XML filename : " + argv[0]);
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File(argv[0]));

            // normalize text representation
            //doc.getDocumentElement ().normalize ();
            //System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());


            NodeList listOfImages = doc.getElementsByTagName("image");
            int totalImages = listOfImages.getLength();
            System.out.println("Total of image files is : " + totalImages);

            for(int img = 0; img < listOfImages.getLength() ; img++){


                Node iNode = listOfImages.item(img);
                
                if(iNode.getNodeType() == Node.ELEMENT_NODE){
                	
                	Element elem = (Element)iNode;
                	NodeList list = elem.getElementsByTagName("resolution");
                    Element tag = (Element)list.item(0);
                    NodeList textFNList = tag.getChildNodes();
                    System.out.println("First Name : " + ((Node)textFNList.item(1)).getNodeValue().trim());
                
                }
                
                if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){


                    Element firstPersonElement = (Element)firstPersonNode;

                    //-------
                    NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
                    Element firstNameElement = (Element)firstNameList.item(0);

                    NodeList textFNList = firstNameElement.getChildNodes();
                    System.out.println("First Name : " + ((Node)textFNList.item(0)).getNodeValue().trim());

                    //-------
                    NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
                    Element lastNameElement = (Element)lastNameList.item(0);

                    NodeList textLNList = lastNameElement.getChildNodes();
                    System.out.println("Last Name : " + ((Node)textLNList.item(0)).getNodeValue().trim());

                    //----
                    NodeList ageList = firstPersonElement.getElementsByTagName("age");
                    Element ageElement = (Element)ageList.item(0);

                    NodeList textAgeList = ageElement.getChildNodes();
                    System.out.println("Age : " + ((Node)textAgeList.item(0)).getNodeValue().trim());

                    //------


                }//end of if clause 


            }//end of for loop with s var 


        }catch (SAXParseException err) {
        System.out.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ());
        System.out.println(" " + err.getMessage ());

        }catch (SAXException e) {
        Exception x = e.getException ();
        ((x == null) ? e : x).printStackTrace ();

        }catch (Throwable t) {
        t.printStackTrace ();
        }
        //System.exit (0);

    }//end of main 


}*/