package eu.simstadt.regionchooser.fast_xml_parser;

import com.ximpleware.AutoPilot;
import com.ximpleware.NavException;
import com.ximpleware.VTDNav;
import com.ximpleware.XPathEvalException;
import com.ximpleware.XPathParseException;


public class BuildingXmlNode
{

	private int buildingOffset;
	private int buildingLength;
	private VTDNav navigator;
	private AutoPilot coordinatesFinder;
	public Double x;
	public Double xMin;
	public Double xMax;
	public Double yMin;
	public Double yMax;
	public Double y;
	private int coordinatesCount = 0;

	public BuildingXmlNode(VTDNav navigator, int buildingOffset, int buildingLength)
			throws XPathParseException, XPathEvalException, NavException {
		this.navigator = navigator;
		this.coordinatesFinder = new AutoPilot(navigator);
		this.buildingLength = buildingLength;
		this.buildingOffset = buildingOffset;
		extractCoordinates();
		//TODO: Get Building ID too, in order to avoid duplicates?
	}

	public boolean hasCoordinates() {
		return coordinatesCount > 0;
	}

	private void extractCoordinates()
			throws XPathParseException, XPathEvalException, NavException {
		double xTotal = 0;
		double yTotal = 0;
		double tempX;
		double tempY;
		double tempXMin = Double.MAX_VALUE;
		double tempXMax = Double.MIN_VALUE;
		double tempYMin = Double.MAX_VALUE;
		double tempYMax = Double.MIN_VALUE;

		coordinatesFinder.selectXPath(".//posList|.//pos");
		while (coordinatesFinder.evalXPath() != -1) {
			long offsetAndLength = navigator.getContentFragment();
			int coordinatesOffset = (int) offsetAndLength;
			int coordinatesLength = (int) (offsetAndLength >> 32);
			String posList = navigator.toRawString(coordinatesOffset, coordinatesLength);
			String[] coordinates = posList.trim().split("\\s+");
			for (int k = 0; k < coordinates.length; k = k + 3) {
				coordinatesCount++;
				tempX = Double.valueOf(coordinates[k]);
				tempY = Double.valueOf(coordinates[k + 1]);
				if (tempX < tempXMin) {
					tempXMin = tempX;
				}
				if (tempY < tempYMin) {
					tempYMin = tempY;
				}
				if (tempX > tempXMax) {
					tempXMax = tempX;
				}
				if (tempY > tempYMax) {
					tempYMax = tempY;
				}
				xTotal += tempX;
				yTotal += tempY;
			}
		}
		this.xMin = tempXMin;
		this.xMax = tempXMax;
		this.yMin = tempYMin;
		this.yMax = tempYMax;
		this.x = xTotal / coordinatesCount;
		this.y = yTotal / coordinatesCount;
	}

	public String toString() {
		try {
			return navigator.toRawString(buildingOffset, buildingLength);
		} catch (NavException ex) {
			return "";
		}
	}
}
