package geometry;

public class Line 
{
	//  A line y = mx+b;
	private double m;
	private double b;
	
	private boolean isVertical;
	private double vertX;
	
	public Line(double x1, double y1, double x2, double y2)
	{
		//  Assumes cartesian coordinates.
		double deltaX = x2 - x1;
		double deltaY = y2 - y1;
		
		if(Math.abs(deltaX) < 0.00001)
		{
			isVertical = true;
			m = 0;
			b = 0;
			vertX = x1;
		}
		else
		{
			isVertical = false;
			m = deltaY/deltaX;
			b = y1 - m*(x1); 
		}
	}
	
	public Line(double m, double b)
	{
		this.m = m;
		this.b = b;
		this.isVertical = false;
	}
	
	public Line createPerpendicularLine(double x1, double y1)
	{
		// creates a perpendicular line to this one which crosses point (x1,y1)
		if(Math.abs(this.m)  < 0.00001)
		{
			// Horizontal line so return vertical line crossing (x1,y1).
			return new Line(x1,y1,x1, (y1+1.0));
		}
		else
		{
			double newM = -1/this.m;
			double newB = y1 - newM*x1;
			
			return new Line(newM, newB);
		}
	}
	
	public double eval(int x) throws ArithmeticException
	{
		if(!isVertical)
			return (m*x) + b;
		else
		{
			throw new ArithmeticException("Cannot evaluate vertical line."); 
		}
			
	}

	public double getM() {
		return m;
	}

	public double getB() {
		return b;
	}
	
	public boolean isVertical() {
		return isVertical;
	}

	public double getVertX() throws Exception 
	{
		if(!this.isVertical)
			throw new Exception("Line is not vertical");
			
		return vertX;
	}
}
