package com.fer.labust.lawnmower.model;

public class Line {
	private Point firstPoint;// (x2,y2)
	private Point secondPoint; // (x1,y1)
	private double gradient;
	private double L;
	private boolean _vodoravan = false;
	private boolean _okomit = false;

	// JEDNADZBA PRAVCA
	// y=kx+l

	// jednadzba pravca kroz dvije tocke
	// y-y1=((y2-y1)/8x2-x1))(x-x1)
	// ili
	// Ax+By+C=0

	// koeficijent nagiba k
	// k= (y2-y1)/(x2-x1)

	// odsjecak na osi x -> l
	// l = y1 - k*x1

	public Line(Point a, Point b) {
		this.setFirstPoint(a);
		this.setSecondPoint(b);
		this.setGradient(odrediNagibPravca());
		this.setL(odrediOdsjecak());
	}

	public Line(double nagib, double odsjecakNaOsiY) {
		this.setGradient(nagib);
		this.setL(odsjecakNaOsiY);
	}

	private double odrediNagibPravca() {
		if (getFirstPoint().getLongitude() == getSecondPoint().getLongitude()) {
			_okomit = true;
			return 0;
		} else if (getFirstPoint().getLatitude() == getSecondPoint()
				.getLatitude()) {
			_vodoravan = true;
			return 0;
		} else {
			double brojnik = getFirstPoint().getLatitude()
					- getSecondPoint().getLatitude();
			double nazivnik = getFirstPoint().getLongitude()
					- getSecondPoint().getLongitude();
			return brojnik / nazivnik;
		}
	}

	private double odrediOdsjecak() {
		if ((getFirstPoint().getLongitude() != getSecondPoint().getLongitude())
				&& (getFirstPoint().getLatitude() != getSecondPoint()
						.getLatitude())) {
			return this.getSecondPoint().getLatitude() - this.getGradient()
					* this.getSecondPoint().getLongitude();
		} else {
			return 0;
		}
	}

	public Point sectionPoint(Line line) {
		Point sectionPoint = new Point();
		double x = 0;
		double y = 0;
		if (_okomit) {
			x = this.getFirstPoint().getLongitude();
			y = line.getGradient() * x + line.getL();
		} else if (_vodoravan) {
			y = this.getFirstPoint().getLatitude();
			x = (y - line.getL()) / line.getGradient();
		} else {
			if (this.getGradient() > line.getGradient()) {
				x = (line.getL() - this.getL())
						/ (this.getGradient() - line.getGradient());
				y = this.getGradient() * x + this.getL();
				sectionPoint.setLongitude(x);
				sectionPoint.setLatitude(y);
			} else {
				x = (this.getL() - line.getL())
						/ (line.getGradient() - this.getGradient());
				y = this.getGradient() * x + this.getL();
			}
		}
		sectionPoint.setLongitude(x);
		sectionPoint.setLatitude(y);
		return sectionPoint;
	}

	public Point getFirstPoint() {
		return firstPoint;
	}

	public void setFirstPoint(Point firstPoint) {
		this.firstPoint = firstPoint;
	}

	public Point getSecondPoint() {
		return secondPoint;
	}

	public void setSecondPoint(Point secondPoint) {
		this.secondPoint = secondPoint;
	}

	public double getGradient() {
		return gradient;
	}

	public void setGradient(double gradient) {
		this.gradient = gradient;
	}

	public double getL() {
		return L;
	}

	public void setL(double l) {
		L = l;
	}
}
