package pythagoras;

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

class exerciseAppletCanvas extends PlotCanvas {
	double A, B, C;
	PlotNode cn;
	
	public exerciseAppletCanvas(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 PlotNode(this, new RealPoint(0, A));
		repaint();
	}
	
	PlotPath asquare;
	PlotPath bsquare;
	PlotPath triangle;
	PlotPath csquare;
	
	boolean ready = true;
	
	public void draw() {
	
		ready = false;
		
		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();
		
		asquare.fill(Color.red);
		asquare.stroke(Color.black);
		
		bsquare.fill(Color.green);
		bsquare.stroke(Color.black);
		
		triangle.stroke(Color.black);
		
		PlotPath drop = new PlotPath(this);
		double d = A*B/C;
		double x = d*A/C, y = d*B/C;
		drop.moveto(0, 0);
		drop.lineto(x, y);
		drop.stroke(Color.black);
		
		PlotPath rect;
		rect = new PlotPath(this);
		rect.moveto(x, y);
		rect.lineto(x+A, y+B);
		rect.lineto(A, A+B);
		rect.lineto(0, A);
		rect.close();
		rect.fill(Color.red);
		rect.stroke(Color.black);
		
		rect = new PlotPath(this);
		rect.moveto(x, y);
		rect.lineto(x+A, y+B);
		rect.lineto(A+B, B);
		rect.lineto(B, 0);
		rect.close();
		rect.fill(Color.green);
		rect.stroke(Color.black);
		cn.draw();
		ready = true;
		
	}
	
	boolean active = false;

	public boolean mouseDown(Event evt, int x, int y) {
		// if (x, y) inside a node set mouseState = MouseActive
		RealPoint P = toRealPoint(x, y);
		if (cn.contains(P)) {
			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;
			cn.locate(q);
			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 exerciseApplet extends Applet {

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

}