package pythagoras;

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

class chineseCanvas extends PlotCanvas {
	double A, B, C;
	PlotNode cn;
	
	public chineseCanvas(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 = 8, H = W*h/w;
		setCorners(-W, -H, W, H);
		// set the origin at the centre
		translate(-(A+B)/2.0, -(A+B)/2.0);
		cn = new PlotNode(this, new RealPoint(B, A+B));
		mkFixedpaths();
	}
	
	PlotPath smallsquare;
	PlotPath bigsquare;
	PlotPath triangle;
	PlotPath csquare;
	
	void mkFixedpaths() {
	
		bigsquare = new PlotPath(this);
		bigsquare.moveto(0, 0);
		bigsquare.lineto((A+B), 0);
		bigsquare.lineto((A+B), (A+B));
		bigsquare.lineto(0, (A+B));
		bigsquare.close();
		
	}
	
	boolean ready = true;

	public void draw() {
	
		ready = false;;
		bigsquare.stroke(Color.black);

		csquare = new PlotPath(this);
		csquare.moveto(A, 0);
		csquare.lineto(A+B, A);
		csquare.lineto(B, (A+B));
		csquare.lineto(0, B);
		csquare.close();
		csquare.fill(Color.red);
		csquare.stroke(Color.black);
		
		triangle = new PlotPath(this);
		triangle.moveto(0, B);
		triangle.rlineto(B, 0);
		triangle.rlineto(0, A);
		triangle.close();
		triangle.stroke(Color.black);
		
		triangle.moveto(B, A+B);
		triangle.rlineto(0, -B);
		triangle.rlineto(A, 0);
		triangle.close();
		triangle.stroke(Color.black);
		
		triangle.moveto(A+B, A);
		triangle.rlineto(-B, 0);
		triangle.rlineto(0, -A);
		triangle.close();
		triangle.stroke(Color.black);
		
		triangle.moveto(A, 0);
		triangle.rlineto(0, B);
		triangle.rlineto(-A, 0);
		triangle.close();
		triangle.stroke(Color.black);
		
		smallsquare = new PlotPath(this);
		double D = B-A;
		smallsquare.moveto(A, B);
		smallsquare.rlineto(D, 0);
		smallsquare.rlineto(0, -D);
		smallsquare.rlineto(-D, 0);
		smallsquare.close();
		smallsquare.fill(Color.pink);
		smallsquare.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);
			if (q.x < 0) q.x = 0;
			else if (q.x > (A+B)) q.x = A+B;
			q.y = (A+B);
			A = (B + A) - q.x;
			B = q.x;
			C = Math.sqrt(A*A + B*B);
			cn.locate(q);
			repaint();
		}
		return true;
	}

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

public class chineseApplet extends Applet {

	double a = 3/2.0, b = 4/2.0;
	chineseCanvas baby;
	
	public void init() {
		setBackground(Color.white);
		// System.out.println("***");
		baby = new chineseCanvas(this, bounds().width, bounds().height,
				 a, b);
		add(baby);
		show();
	}

}