package de.hft.stuttgart.citygml.green.osm;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.FeatureSource;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.locationtech.jts.geom.Point;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;

public class TreeKatasterData {
	
	public static final double TRUNK_PERCENTAGE = 0.2;
	public static final double CROWN_PERCENTAGE = 1 - TRUNK_PERCENTAGE;
	
	private List<Tree> trees;
	
	public static TreeKatasterData parseTreeKatasterData(Path path) throws IOException {
		TreeKatasterData result = new TreeKatasterData();
		Map<String, Object> readParameters = new HashMap<>();
		readParameters.put("url", path.toUri().toURL());
		readParameters.put("charset", StandardCharsets.UTF_8);
		DataStore dataStore = DataStoreFinder.getDataStore(readParameters);
		String typeName = dataStore.getTypeNames()[0];

		FeatureSource<SimpleFeatureType, SimpleFeature> source = dataStore.getFeatureSource(typeName);

		FeatureCollection<SimpleFeatureType, SimpleFeature> collection = source.getFeatures();
		try (FeatureIterator<SimpleFeature> features = collection.features()) {
			while (features.hasNext()) {
				SimpleFeature feature = features.next();
				Tree tree = new Tree();

				Point p = (Point) feature.getAttribute("the_geom");
				tree.setPoint(p);

				String type = feature.getAttribute("Bezeichnun").toString();
				tree.setType(type);

				Object treeHeightObject = feature.getAttribute("Baumhöhe");
				if (treeHeightObject == null) {
					continue;
				}
				int treeHeight = Integer.parseInt(treeHeightObject.toString());
				double crownHeight = CROWN_PERCENTAGE * treeHeight;
				double trunkHeight = TRUNK_PERCENTAGE * treeHeight;
				tree.setCrownHeight(crownHeight);
				tree.setTrunkHeight(trunkHeight);

				Object crownWidth = feature.getAttribute("Kronenbrei");
				if (crownWidth == null) {
					continue;
				}
				tree.setCrownRadius(Float.parseFloat(crownWidth.toString()) / 2);
				Object trunkCirc = feature.getAttribute("Stammumfan");
				if (trunkCirc == null) {
					continue;
				}
				tree.setTrunkRadius(Integer.parseInt(trunkCirc.toString()) / (2 * Math.PI) / 100);

				result.getTrees().add(tree);
			}
		}
		return result;
	}
	
	public List<Tree> getTrees() {
		if (trees == null) {
			trees = new ArrayList<>();
		}
		return trees;
	}

}
