package pythagoras;

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

class SimilarityAppletCanvas extends PlotCanvas {
	RealPoint P0, P1, P2;
	PlotNode cn;
	
	public SimilarityAppletCanvas(Applet a, int w, int h, double x, double y) {
		super(a, w, h);
		double W = 6, H = W*h/w;
		setCorners(-W, -H, W, H);
		P0 = new RealPoint(-1.2, -1);
		P1 = new RealPoint( 0.5, -1);
		P2 = new RealPoint( 0,  1);
		
		cn = new PlotNode(this, P2);
		repaint();
	}
	
	PlotPath triangle;
	
	boolean ready = true;
	
	public void draw() {
		ready = false;
		triangle = new PlotPath(this);
		triangle.moveto(P0.x, P0.y);
		triangle.lineto(P1.x, P1.y);
		triangle.lineto(P2.x, P2.y);
		triangle.close();
		triangle.fill(Color.pink);
		triangle.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;
	}
	
	int border = 10;

	public boolean mouseDrag(Event evt, int x, int y) {
		if (active && ready) {
			if (y > height-border) y = height-border;
			else if (y < border) y = border;
			RealPoint q = toRealPoint(x, y);
			q.x = 0;
			double c = q.y/P2.y;
			if (c == 0.0) c = 0.01;
			P0.scale(c);
			P1.scale(c);
			P2.scale(c);
			cn.locate(P2);
			repaint();
		}
		return true;
	}

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

public class SimilarityApplet extends Applet {

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

}