/*-
 *  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.checks.geometry;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import de.hft.stuttgart.citydoctor2.check.Check;
import de.hft.stuttgart.citydoctor2.check.CheckError;
import de.hft.stuttgart.citydoctor2.check.CheckId;
import de.hft.stuttgart.citydoctor2.check.CheckResult;
import de.hft.stuttgart.citydoctor2.check.RequirementType;
import de.hft.stuttgart.citydoctor2.check.Requirement;
import de.hft.stuttgart.citydoctor2.check.ResultStatus;
import de.hft.stuttgart.citydoctor2.check.error.AllPolygonsWrongOrientationError;
import de.hft.stuttgart.citydoctor2.checks.util.CollectionUtils;
import de.hft.stuttgart.citydoctor2.datastructure.Geometry;
import de.hft.stuttgart.citydoctor2.datastructure.GeometryType;
import de.hft.stuttgart.citydoctor2.datastructure.Polygon;
import de.hft.stuttgart.citydoctor2.math.Ray;
import de.hft.stuttgart.citydoctor2.math.Triangle3d;
import de.hft.stuttgart.citydoctor2.math.Vector3d;
import de.hft.stuttgart.citydoctor2.tesselation.TesselatedPolygon;

/**
 * Checks whether all polygons have the wrong orientation.
 * 
 * @author Matthias Betz
 *
 */
public class AllPolygonsWrongOrientationCheck extends Check {

	private static final List<CheckId> dependencies;

	static {
		ArrayList<CheckId> deps = new ArrayList<>();
		deps.add(CheckId.C_GE_R_TOO_FEW_POINTS);
		deps.add(CheckId.C_GE_R_NOT_CLOSED);
		deps.add(CheckId.C_GE_R_DUPLICATE_POINT);
		deps.add(CheckId.C_GE_R_SELF_INTERSECTION);
		deps.add(CheckId.C_GE_P_INTERIOR_DISCONNECTED);
		deps.add(CheckId.C_GE_P_INTERSECTING_RINGS);
		deps.add(CheckId.C_GE_P_NON_PLANAR);
		deps.add(CheckId.C_GE_S_TOO_FEW_POLYGONS);
		deps.add(CheckId.C_GE_S_NOT_CLOSED);
		deps.add(CheckId.C_GE_S_MULTIPLE_CONNECTED_COMPONENTS);
		deps.add(CheckId.C_GE_S_NON_MANIFOLD_EDGE);
		deps.add(CheckId.C_GE_S_NON_MANIFOLD_VERTEX);
		deps.add(CheckId.C_GE_S_SELF_INTERSECTION);

		dependencies = Collections.unmodifiableList(deps);
	}

	@Override
	public void check(Geometry g) {
		// only check solids
		if (g.getType() != GeometryType.SOLID) {
			return;
		}
		boolean isOutwardOriented = geometryIsOutwardOrientedJava(g);
		CheckResult cr;
		if (isOutwardOriented) {
			cr = new CheckResult(this, ResultStatus.OK, null);
		} else {
			CheckError err = new AllPolygonsWrongOrientationError(g);
			cr = new CheckResult(this, ResultStatus.ERROR, err);
		}
		g.addCheckResult(cr);
	}

	private boolean geometryIsOutwardOrientedJava(Geometry g) {
		Vector3d[] bbox = g.calculateBoundingBox().getBox();

		// tesselate polygons
		ArrayList<TesselatedPolygon> tessPolygons = new ArrayList<>();
		for (Polygon p : g.getPolygons()) {
			tessPolygons.add(p.tesselate());
		}
		if (tessPolygons.isEmpty()) {
			throw new IllegalStateException("No polygons found in geometry");
		}
		// get any triangle to construct a point in any polygon
		TesselatedPolygon p1 = null;
		for (TesselatedPolygon tessPoly : tessPolygons) {
			if (!tessPoly.getTriangles().isEmpty()) {
				p1 = tessPoly;
				break;
			}
		}
		if (p1 == null) {
			throw new IllegalStateException("No polygon could be triangulated");
		}

		Triangle3d t = findSuitableTriangle(p1);
		// find the centroid of a triangle
		Vector3d centroid = t.getCentroid();
		// create a point outside of the geometry
		Vector3d outsidePoint = bbox[0].minus(Vector3d.X, 5).minus(Vector3d.Y, 5).minus(Vector3d.Z, 5);
		// create a second point outside of the geometry
		// the check can fail if the building is exactly oriented so that the ray is
		// parallel to a side of the building
		// in order to avoid this we check two rays, if one of those says it is oriented
		// correctly it is oriented correctly
		Vector3d secondOutsidePoint = bbox[0].minus(Vector3d.X, 5).minus(Vector3d.Y, 10).minus(Vector3d.Z, 5);
		return checkIfGeometryIsWrongOriented(tessPolygons, centroid, outsidePoint)
				|| checkIfGeometryIsWrongOriented(tessPolygons, centroid, secondOutsidePoint);
	}

	private boolean checkIfGeometryIsWrongOriented(ArrayList<TesselatedPolygon> tessPolygons, Vector3d centroid,
			Vector3d outsidePoint) {
		// centroid point is now in the polygon, calculate the direction vector of the
		// ray
		Vector3d outsidePointDirection = centroid.minus(outsidePoint);
		// construct a ray to check for intersections
		Ray ray = new Ray(outsidePoint, outsidePointDirection);
		// check for intersections, store closest polygon in tessPoly
		TesselatedPolygon tessPoly = null;
		double distance = Double.MAX_VALUE;
		for (TesselatedPolygon tp : tessPolygons) {
			Vector3d intersection = ray.intersectsPolygon(tp);
			if (intersection != null) {
				// calculate distance between intersection point and outsidePoint
				double d = outsidePoint.getDistance(intersection);
				// check if polygon is closer
				if (d < distance) {
					tessPoly = tp;
					distance = d;
				}
			}
		}
		if (tessPoly == null) {
			throw new IllegalStateException("Constructed a ray that does not intersect any polygon");
		}
		// calculate normal of the closest polygon
		Vector3d normal = tessPoly.getOriginal().calculateNormalNormalized();
		// calculate cos(gamma) of normal and ray direction, the normal is normalized,
		// don't need to get the length
		double cosAngle = outsidePointDirection.dot(normal) / outsidePointDirection.getLength();
		// cos is negative = ok
		return cosAngle <= 0;
	}

	private Triangle3d findSuitableTriangle(TesselatedPolygon p1) {
		Triangle3d t = p1.getTriangles().get(0);
		double maxArea = t.getArea();
		for (Triangle3d tri : p1.getTriangles()) {
			double area = tri.getArea();
			if (area > maxArea) {
				maxArea = area;
				t = tri;
			}
		}
		return t;
	}

	@Override
	public List<CheckId> getDependencies() {
		return dependencies;
	}
	
	@Override
	public Set<Requirement> appliesToRequirements() {
		return CollectionUtils.singletonSet(Requirement.R_GE_S_ALL_POLYGONS_WRONG_ORIENTATION);
	}

	@Override
	public RequirementType getType() {
		return RequirementType.GEOMETRY;
	}

	@Override
	public Check createNewInstance() {
		return new AllPolygonsWrongOrientationCheck();
	}

	@Override
	public CheckId getCheckId() {
		return CheckId.C_GE_S_ALL_POLYGONS_WRONG_ORIENTATION;
	}

}
