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


public class GmStraight {

	private Point3d org;
	private UnitVector3d dir;

	public GmStraight(Point3d org, Vector3d dir) {
		this.org = org;
		this.dir = dir.toUnitVector();
	}

	public GmStraight(Point3d org, UnitVector3d dir) {
		this.org = org;
		this.dir = dir;
	}

	public ProjectedPoint3d project(Point3d origin) {
		Vector3d v2Origin = origin.minus(org);

		double length = v2Origin.getLength();
		if (length < Global.getTolPointsEquals()) {
			return new ProjectedPoint3d(origin, 0.0);
		}

		double parameter = dir.dot(UnitVector3d.of(v2Origin)) * length;
		Point3d foot = evaluate(parameter);
		return new ProjectedPoint3d(foot, parameter);
	}

	public Point3d evaluate(double param) {
		return org.plus(dir.mult(param));
	}

	public UnitVector3d getDir() {
		return dir;
	}

	public boolean isColinear(GmStraight straight2, double angleEpsilon, double epsilon) {
		UnitVector3d rDir1 = getDir();
		UnitVector3d rDir2 = straight2.getDir();

		if ((!Vector3d.areParallel(rDir1, rDir2, angleEpsilon))
				&& (!Vector3d.areAntiParallel(rDir1, rDir2, angleEpsilon))) {

			return false;
		}

		Point3d rOrigin1 = getOrigin();

		Point3d foot1 = straight2.project(rOrigin1).getPoint();
		if ((foot1.minus(rOrigin1)).getLength() > epsilon) {
			return false;
		}

		Point3d rOrigin2 = straight2.getOrigin();

		Point3d foot2 = project(rOrigin2).getPoint();
		if ((foot2.minus(rOrigin2)).getLength() > epsilon) {
			return false;
		}

		return true;
	}

	public Point3d getOrigin() {
		return org;
	}

}
