package org.gcube.portlets.user.gisviewer.test.client;

import java.net.URL;

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

import org.gcube.portlets.user.gisviewer.server.datafeature.CXml;
import org.gcube.portlets.user.gisviewer.server.datafeature.CXmlManager;
import org.w3c.dom.Document;

public class DocumentParser {
	
	private static final String ROW_TAG = "gml:featureMembers";
	private static String EXCEPTION_TAG_RESPONSE = "ows:ExceptionReport";

	// PARSE TEST
	/**
	 * Parses the.
	 */
	private static void parse() {
		String layer = "aquamaps:environments";
		String url = "http://geoserver2.d4science.research-infrastructures.eu/geoserver/wfs?service=wfs&version=1.1.0&request=GetFeature&typeName="+layer+"&bbox=0,0,180,1";
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db;
			db = dbf.newDocumentBuilder();
			Document doc = db.parse(new URL(url).openStream());

			CXml root = new CXml(doc);

			if (root.tagName().equals(EXCEPTION_TAG_RESPONSE )) {
				;
			}

			System.out.println("ROOT:" + root.tagName());

			root.child("gml:featureMembers").children().each(new CXmlManager() {
				@Override
				public void manage(int index, CXml cxml) {
					cxml.children().each(new CXmlManager() {
						@Override
						public void manage(int index, CXml cxml) {
							String tagName = cxml.tagName();
							String value = cxml.getText();
							if (value!=null) {
								if (tagName.contains(":")) {
									tagName = tagName.split(":", 2)[1];
								}
								System.out.println("\t"+tagName+" = "+value);
							}
						}
					});
					System.out.println();
				}
			});

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
