package pythagoras;

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

class pythagorasSimilarityAppletCanvas extends PlotCanvas {
	double A, B, C;
	double dx, dy;
	PlotNode cn;
	
	public pythagorasSimilarityAppletCanvas(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);
		initd();
		
		double W = 8, 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));
		Font SymbolFont = new Font("Helvetica", Font.ITALIC, 16);
		setFont(SymbolFont);
		repaint();
	}
	
	void initd() {
		double d = A*B/C;
		dx = A*d/C;
		dy = B*d/C;
	}
	
	PlotPath triangle;
	PlotPath trianglea;
	PlotPath triangleb;
	
	boolean ready = true;
	
	public void draw() {
		ready = true;
		triangle = new PlotPath(this);
		triangle.moveto(0, 0);
		triangle.lineto(B, 0);
		triangle.lineto(0, A);
		triangle.close();
		triangle.fill(Color.pink);
		// triangle.stroke(Color.black);
		
		trianglea = new PlotPath(this);
		trianglea.moveto(0, 0);
		trianglea.lineto(dx, dy);
		trianglea.lineto(0, A);
		trianglea.close();
		trianglea.stroke(Color.black);
		
		triangleb = new PlotPath(this);
		triangleb.moveto(0, 0);
		triangleb.lineto(dx, dy);
		triangleb.lineto(B, 0);
		triangleb.close();
		triangleb.stroke(Color.black);
		
		RealPolygon rp = pixel();
		double x, y, 
			DX = Math.abs(rp.b[1].x - rp.b[0].x), 
			DY = Math.abs(rp.b[3].y - rp.b[0].y);
		double deltax = 4*A*DX/C;
		double deltay = 4*B*DY/C;
		
		x = dx/2.0 + deltax;
		y = (A + dy)/2.0 + deltay;
		drawString("x", x, y);
		
		x = (dx+B)/2.0 + deltax;
		y = dy/2.0 + deltay;
		drawString("c-x", x, y);
		
		x = -16*DX;
		y = (A - 8*DY)/2.0;
		drawString("a", x, y);
		
		x = (B- 8*DX)/2.0;
		y = -16*DY;
		drawString("b", x, y);
		
		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 && ready) {
			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);
			initd();
			repaint();
		}
		return true;
	}

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

public class pythagorasSimilarityApplet extends Applet {

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

}