import java.awt.*;
/**
 * PatchLine, a ViewObject, a line between ConnectionBoxes represents a patch.
 */
public class PatchLine extends ViewObject {
	/**
	 * The inputBox (the start) of the Line
	 * */
	ConnectionBox inputBox;
	/**
	 * The outputBox (the end) of the Line
	 * */
	ConnectionBox outputBox;
	/**
	 * The start point the inputBox output node
	 * */
	Point pointS=null;
	/**
	 * The end point the outputBox input node
	 * */
	Point pointE=null;
	/**
	 * Default Constructor
	 * */
	public PatchLine() {
	}
	/**
	 * Default Constructor, sets the ConnectionBoxes for the relationship.
	 * @param inputBox the input ConnectionBox
	 * @param outputBox the output ConnectionBox
	 * */
	public PatchLine(ConnectionBox inputBox,ConnectionBox outputBox) {
		this.inputBox = inputBox;
		this.outputBox = outputBox;
	}
	/**
	 * PaintOn the graphics g
	 * */
	public void paintOn(Graphics g) {
		getPoints();
		g.setColor(Color.GREEN);
		g.drawLine((int)pointS.getX(),(int)pointS.getY(),(int)pointE.getX(),(int)pointE.getY());
	}
	/**
	 * Is this object draggable.
	 * */
	public boolean draggable() {
		return false;
	}
	/**
	 * get the points from the ConnectionBoxes.
	 * */
	void getPoints() {
		pointS = inputBox.getOutputKnobLocation();
		pointE = outputBox.getInputKnobLocation();
	}
	/**
	 * gets the input ConnectionBox.
	 * */
	public ConnectionBox getInput() {
		return inputBox;
	}
	/**
	 * gets the output ConnectionBox.
	 * */
	public ConnectionBox getOutput() {
		return outputBox;
	}
	/**
	 * sets the input ConnectionBox. 
	 * @param i the inputBox
	 * */
	public void setInput(ConnectionBox i) {
		inputBox = i;
	}
	/**
	 * sets the output ConnectionBox. 
	 * @param i the outputBox
	 * */
	public void setOutput(ConnectionBox o) {
		outputBox = o;
	}
	/**
	 * Was this line clicked on? has a small margin of error 
	 * */
	public boolean wasClicked(int x,int y) {
		getPoints();
		int X1 = (int)pointS.getX();
		int X2 = (int)pointE.getX();
		int Y1 = (int)pointS.getY();
		int Y2 = (int)pointE.getY();
		if (X1 > X2) { //swap
			int tmp = X1;
			X1 = X2;
			X2 = tmp;
			tmp = Y1;
			Y1 = Y2;
			Y2 = tmp;
		}
		if (!(x >= X1 && x <= X2 &&  (Y1 >= y && y >= Y2 || Y1 <= y && y <= Y2) )) {
			return false;
		}
		//now the point is in the rectangle
		float slope = (1.0f*(Y2-Y1))/(X2 - X1);
		x = x-X1;
		X2 -= X1;
		X1 = 0;
		float y2 = (float)(Y1 + (slope*x)); //  y = slope*x + Y1
		if (Math.abs(y2 - y) <= 4) {
			//CLICKED
			return true;
		}
		return false;
	}
	/**
	 * Hashcode based on the input and output ids
	 * */
	public int hashCode() {
		String hashCode = inputBox.getConnection().getID()+"-"+outputBox.getConnection().getID();
		return hashCode.hashCode();
	}
}

