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

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

import de.hft.stuttgart.citydoctor2.datastructure.LinearRing;
import de.hft.stuttgart.citydoctor2.datastructure.Vertex;

/**
 * A ring moved by an offset. Used to avoid numerical inaccuracies
 * 
 * @author Matthias Betz
 *
 */
public class MovedRing {

	private List<Vector3d> vertices;
	private LinearRing original;

	public static MovedRing ofRing(LinearRing ring, Vector3d movedBy) {
		MovedRing indRing = new MovedRing();
		indRing.original = ring;
		for (Vertex v : ring.getVertices()) {
			Vector3d movedV = new Vector3d(v.getX() - movedBy.getX(), v.getY() - movedBy.getY(),
					v.getZ() - movedBy.getZ());
			indRing.addVertex(movedV);
		}
		return indRing;
	}
	
	private MovedRing() {
		vertices = new ArrayList<>();
	}

	public LinearRing getOriginal() {
		return original;
	}

	private void addVertex(Vector3d v) {
		vertices.add(v);
	}

	public List<Vector3d> getVertices() {
		return vertices;
	}

	/**
	 * Checks whether a point is inside this ring. A point on the edge does count as
	 * inside.
	 * 
	 * @param v the point.
	 * @return true if the point is inside or on an edge, false if it is outside.
	 */
	public boolean isPointInside(Vector3d v) {
		// project to 2d ring
		ProjectionAxis axis = ProjectionAxis.of(this);
		Ring2d projectedRing = Ring2d.of(this, axis);
		Vector2d point = axis.project(v);
		return projectedRing.containsPoint(point);
	}

	/**
	 * Calculates the normal vector of the ring. Method by Newell. If the Newell
	 * method would return a (0, 0, 0) vector a cross product is formed from the
	 * first 3 vertices. If there are no 3 vertices available (1, 0, 0) is returned.
	 * 
	 * @return the normal as a normalized vector
	 */
	public UnitVector3d calculateNormalNormalized() {
		return original.calculateNormalNormalized();
	}
}
