/*-
 *  Copyright 2020 Beuth Hochschule für Technik Berlin, Hochschule für Technik Stuttgart
 * 
 *  This file is part of CityDoctor2.
 *
 *  CityDoctor2 is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  CityDoctor2 is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with CityDoctor2.  If not, see <https://www.gnu.org/licenses/>.
 */
package de.hft.stuttgart.citydoctor2.parser;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import de.hft.stuttgart.citydoctor2.math.Vector3d;

/**
 * Handler to find epsg code in CityGML files
 * 
 * @author Matthias Betz
 *
 */
public class CityGmlHandler extends DefaultHandler {

	private boolean foundEnvelope = false;

	private Vector3d lowerCorner;
	private Vector3d upperCorner;
	private String epsg;

	private boolean nextContentIsLowerCorner = false;
	private boolean nextContentIsUpperCorner = false;

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		if (foundEnvelope) {
			if (qName.endsWith("lowerCorner")) {
				nextContentIsLowerCorner = true;
			} else if (qName.endsWith("upperCorner")) {
				nextContentIsUpperCorner = true;
			}
		} else if (qName.endsWith("Envelope")) {
			foundEnvelope = true;
			epsg = attributes.getValue("srsName");
		}
	}

	public Vector3d getLowerCorner() {
		return lowerCorner;
	}

	public Vector3d getUpperCorner() {
		return upperCorner;
	}

	public String getEpsg() {
		return epsg;
	}

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		if (nextContentIsLowerCorner) {
			lowerCorner = parsePoint(ch, start, length);
			nextContentIsLowerCorner = false;
		} else if (nextContentIsUpperCorner) {
			upperCorner = parsePoint(ch, start, length);
			nextContentIsUpperCorner = false;
			throw new EnvelopeFoundException("Found envelope, stop parsing");
		}
	}

	private Vector3d parsePoint(char[] ch, int start, int length) {
		String s = new String(ch, start, length);
		String[] coords = s.split("\\s+");
		double x = Double.parseDouble(coords[0]);
		double y = Double.parseDouble(coords[1]);
		double z = Double.parseDouble(coords[2]);
		return new Vector3d(x, y, z);
	}

}
