/* $Id: XMLToLineConverter.java 247 2011-06-29 20:58:52Z minao $ */
package smart_gs.util;

import java.awt.geom.Point2D;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
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.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import smart_gs.logical.GSResource;
import smart_gs.logical.LineSegment;
import smart_gs.logical.Spread;

public class XMLToLineConverter {
	
	private Spread spread;
	
	public XMLToLineConverter(Spread spread){
		this.spread = spread;
	}
	
	public List<LineSegment> getLines(File file){
		List<LineSegment> results = new ArrayList<LineSegment>();
		DocumentBuilder builder = null;
		Document document = null;
		try {
			builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			document = builder.parse(file);
			NodeList lines = document.getElementsByTagName("vertexes");
			for(int i=0;i<lines.getLength();i++){
				if(lines.item(i).getNodeType() == Node.ELEMENT_NODE){
					LineSegment segment = this.getLineSegment((Element)lines.item(i), i);
					results.add(segment);
				}
			}
		}
		catch(ParserConfigurationException e){
			
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
		//	e.printStackTrace();
		}
		return results;
	}
	private LineSegment getLineSegment(Element element, int index){
		List<Point2D> points = new ArrayList<Point2D>();
		String uri = element.getAttribute("uri");
		String originalURI = element.getAttribute(GSResource.ORIGINAL_URI);
		NodeList nodes = element.getElementsByTagName("vertex");
		double x = 0.0 ,y = 0.0;
		for(int i=0;i<nodes.getLength();i++){
			if(nodes.item(i).getNodeType() == Node.ELEMENT_NODE){
				Element e = (Element)nodes.item(i);
				NodeList childs = e.getChildNodes();
				for(int j=0;j<childs.getLength();j++){
					if(childs.item(j).getNodeType() == Node.ELEMENT_NODE){
						Element elem = (Element)childs.item(j);
						if(elem.getNodeName().equals("x")){
							x = new Double(elem.getTextContent());
						}
						else if(elem.getNodeName().equals("y")){
							y = new Double(elem.getTextContent());
							points.add(new Point2D.Double(x,y));
						}
					}
				}
			}
		}
		return new LineSegment(spread,points,uri,originalURI,index);

	}
}
