package pythagoras;

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

class leonardoAppletCanvas extends PlotCanvas {
	double A, B, C;
	PlotNode cn;
	
	public leonardoAppletCanvas(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();
	}
	
	boolean ready = true;
	
	public void draw() {
		ready=false;
		
		// a square
		PlotPath p = new PlotPath(this);
		p.moveto(0, 0);
		p.rlineto(0, A);
		p.rlineto(-A, 0);
		p.rlineto(0, -A);
		p.close();
		p.stroke(Color.black);
		
		// b square
		p = new PlotPath(this);
		p.moveto(0, 0);
		p.rlineto(B, 0);
		p.rlineto(0, -B);
		p.rlineto(-B, 0);
		p.close();
		p.stroke(Color.black);

		// c square
		p = new PlotPath(this);
		p.moveto(0, A);
		p.lineto(B, 0);
		p.lineto(A+B, B);
		p.lineto(A, A+B);
		p.close();
		p.stroke(Color.black);
		
		// triangle
		p = new PlotPath(this);
		p.moveto(0, 0);
		p.lineto(B, 0);
		p.lineto(0, A);
		p.close();
		p.stroke(Color.black);
		
		// region 1
		p = new PlotPath(this);
		p.moveto(0, 0);
		p.lineto(B, 0);
		p.lineto(A+B, B);
		p.rlineto(0, A);
		p.close();
		p.fill(Color.pink);
		p.stroke(Color.black);
		
		// region 2
		p = new PlotPath(this);
		p.moveto(-A, 0);
		p.lineto(0, -B);
		p.lineto(B, -B);
		p.lineto(-A, A);
		p.close();
		p.fill(Color.pink);
		p.stroke(Color.black);
	
		p = new PlotPath(this);
		p.moveto(0, 0);
		p.lineto(0, A);
		p.lineto(A, A+B);
		p.rlineto(B, 0);
		p.close();
		// p.fill(Color.red);
		p.stroke(Color.black);

		p = new PlotPath(this);
		p.moveto(-A, A);
		p.rlineto(A, 0);
		p.lineto(B, 0);
		p.rlineto(0, -B);
		p.close();
		// p.fill(Color.red);
		p.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)) {
			System.out.println("!");
			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 leonardoApplet extends Applet {

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

}