package pythagoras;

import java.applet.*;
import java.awt.*;
import psplot.*;
import real.*;

class pythagorasAppletCanvas extends PlotCanvas {
	double A, B, C;
	controlNode cn;
	
	public pythagorasAppletCanvas(Applet a, int w, int h, double x, double y) {
		super(a, w, h);
		A = x; B = y;
		C = Math.sqrt(A*A + B*B);
		double W = 16, H = W*h/w;
		setCorners(-W, -H, W, H);
		// set the origin at the centre
		translate(-A, -A/2.0);
		cn = new controlNode(this, new RealPoint(0, A));
		mkFixedpaths();
		repaint();
	}
	
	PlotPath asquare;
	PlotPath bsquare;
	PlotPath triangle;
	PlotPath csquare;
	
	void mkFixedpaths() {
	}
	
	public void draw() {
		
		csquare = new PlotPath(this);
		csquare.moveto(0, A);
		csquare.rlineto(B, -A);
		csquare.rlineto(A, B);
		csquare.rlineto(-B, A);
		csquare.close();
		
		asquare = new PlotPath(this);
		asquare.moveto(0, 0);
		asquare.rlineto(0, A);
		asquare.rlineto(-A, 0);
		asquare.rlineto(0, -A);
		asquare.close();
		
		bsquare = new PlotPath(this);
		bsquare.moveto(0, 0);
		bsquare.rlineto(B, 0);
		bsquare.rlineto(0, -B);
		bsquare.rlineto(-B, 0);
		bsquare.close();
		
		triangle = new PlotPath(this);
		triangle.moveto(0, 0);
		triangle.lineto(B, 0);
		triangle.lineto(0, A);
		triangle.close();
		
		csquare.fill(Color.blue);
		csquare.stroke(Color.black);
		
		asquare.fill(Color.red);
		asquare.stroke(Color.black);
		
		bsquare.fill(Color.green);
		bsquare.stroke(Color.black);
		
		triangle.stroke(Color.black);
		cn.draw();
	}
	
	boolean active = false;

	public boolean mouseDown(Event evt, int x, int y) {
		// if (x, y) inside a node set mouseState = MouseActive
		if (cn.contains(x, y)) {
			active = true;
		}
		return true;
	}

	public boolean mouseDrag(Event evt, int x, int y) {
		if (active) {
			RealPoint q = toRealPoint(x, y);
			q.x = 0;
			if (q.y > C) q.y = C;
			if (q.y < 0.0) q.y = 0.0;
			Point P = toPoint(q);
			cn.locate(P.x, P.y);
			A = q.y;
			B = Math.sqrt(C*C - A*A);
			repaint();
		}
		return true;
	}

	public boolean mouseUp(Event evt, int x, int y) {
		// set nodes inactive
		active = false;
		return true;
	}
}

public class pythagorasApplet extends Applet {

	double a = 3, b = 4;
	pythagorasAppletCanvas baby;
	
	public void init() {
		setBackground(Color.white);
		baby = new pythagorasAppletCanvas(this, bounds().width, bounds().height, a, b);
		add(baby);
		show();
	}

}