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

import java.util.ArrayList;
import java.util.List;

import de.hft.stuttgart.citydoctor2.check.Check;
import de.hft.stuttgart.citydoctor2.check.CheckResult;
import de.hft.stuttgart.citydoctor2.check.ResultStatus;
import de.hft.stuttgart.citydoctor2.check.error.SurfaceUnfragmentedError;
import de.hft.stuttgart.citydoctor2.datastructure.BoundarySurface;
import de.hft.stuttgart.citydoctor2.datastructure.Geometry;
import de.hft.stuttgart.citydoctor2.datastructure.Polygon;
import de.hft.stuttgart.citydoctor2.math.Vector3d;

/**
 * Utility class for checking whether a boundary surface has different normals
 * in their polygons.
 * 
 * @author Matthias Betz
 *
 */
public class UnfragmentedCheck {

	private UnfragmentedCheck() {

	}

	/**
	 * This checks each geometry in a boundary surface whether the normals deviate
	 * too much from the average of all normals in the same geometry.
	 * 
	 * @param c     the check from which this method is called, needed to construct
	 *              the check result
	 * @param bs    the boundary surface containing the geometries.
	 * @param delta the maximum angle which the normals may deviate. In radians.
	 * @return the check result with either the result ok, or error
	 */
	public static CheckResult checkForFragmentedBoundarySurfaces(Check c, BoundarySurface bs, double delta) {
		for (Geometry geom : bs.getGeometries()) {
			List<Vector3d> normals = new ArrayList<>();
			for (Polygon p : geom.getPolygons()) {
				normals.add(p.calculateNormalNormalized());
			}
			double x = 0;
			double y = 0;
			double z = 0;
			for (Vector3d n : normals) {
				x += n.getX();
				y += n.getY();
				z += n.getZ();
			}
			x = x / normals.size();
			y = y / normals.size();
			z = z / normals.size();
			Vector3d averageNormal = new Vector3d(x, y, z);
			for (Vector3d n : normals) {
				double dot = averageNormal.dot(n);
				double acos = Math.acos(dot);
				if (acos > delta) {
					SurfaceUnfragmentedError err = new SurfaceUnfragmentedError(bs, acos);
					return new CheckResult(c, ResultStatus.ERROR, err);
				}
			}
		}
		return new CheckResult(c, ResultStatus.OK, null);
	}
}
