import figure.*;
import java.awt.*;
import javax.swing.*;

public class TangentLine extends FigurePanel implements Mover, Function {
    GraphicalLine tangent;
    GraphicalPoint point;
    public TangentLine() {
	super(-2, -2, 2, 2);
	setBackground(Color.white);

        Grid grid = new Grid();
        grid.setColor(Color.lightGray);
        add(grid);
        
        Axes axes = new Axes();
        add(axes);


	GraphicalFunction gf = new GraphicalFunction(this, null);
	gf.setSteps(50);
	gf.setColor(Color.blue);
	gf.setStroke(new BasicStroke(2f));
	add(gf);

	GraphicalPoint point = new GraphicalPoint(0, 0);
	point.setSize(3);
	point.setStyle(GraphicalPoint.CIRCLE);
	point.setColor(Color.red);

	tangent = new GraphicalLine(0, 0, 0, 0);
	tangent.setColor(new Color(0.7f, 0.2f, 0.2f));
	tangent.setStroke(new BasicStroke(2));
	add(tangent);
	add(point);

	move(point, 0, 0);

	addMoveable(point, this);
    }

    public void move(Moveable m, double x, double y) {
	y = valueAt(x, null);
	((GraphicalPoint) m).setPoint(x, y);
	double slope = deriv(x);
	tangent.setPoints(bbox.llx, (bbox.llx - x)*slope + y,
		     bbox.urx, (bbox.urx - x)*slope + y);
    }
	
    public double valueAt(double x, double[] params) {
        return Math.exp(-x/2)*Math.sin(2*x);
    }

    public double deriv(double x) {
	return -1./2*Math.exp(-x/2)*Math.sin(2*x) + 2*Math.exp(-x/2)*Math.cos(2*x);
    }

    public static void main(String[] args) {
	TangentLine tangent = new TangentLine();
	tangent.setPreferredSize(new Dimension(300, 300));
        JFrame frame = new JFrame("TangentLine");
	frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	frame.getContentPane().add(tangent);

        frame.pack();
        frame.setVisible(true);
    }

}


