import java.awt.*;
import java.awt.event.*;

public class MouseMandelRenderArea extends MandelRenderArea implements MouseListener, MouseMotionListener {
	
	protected double dcx, dcy, dwx, dwy, ratio;
	protected int clx, cly;
	protected MandelApplet parent;
	protected boolean area, temparea;
	
	public MouseMandelRenderArea(MandelApplet p, int w, int h, double r, boolean a) {
		super(w, h);
		parent = p;
		ratio = r;
		area = a;
		temparea = a;
		setArea(-.6, 0, 3, 3);
		addMouseListener(this);
		addMouseMotionListener(this);
		setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
	}
	
	public void paint(Graphics g) {
		super.paint(g);
		if (temparea) {
			g.setColor(Color.white);
			int x = (int)(((dcx - cx)/wx + .5)*(width-1));
			int y = (int)(((cy - dcy)/wy + .5)*(height-1));
			int w = (int)(dwx/wx*width);
			int h = (int)(dwy/wy*height);
			g.drawLine(x-3, y, x+3, y);
			g.drawLine(x, y-3, x, y+3);
			g.drawRect(x-w/2, y-h/2, w-1, h-1);
		}
	}
	
	public void setArea(double x, double y, double w, double h) {
		dcx = x;
		dcy = y;
		dwx = w;
		dwy = (ratio == 0) ? h : ratio*dwx;
		repaint();
	}
	
	public void mouseClicked(MouseEvent e) {}
	public void mouseEntered(MouseEvent e) {}
	public void mouseExited(MouseEvent e) {}
	public void mousePressed(MouseEvent e) {
		temparea = true;
		clx = e.getX();
		cly = e.getY();
		dcx = cx + ((double)clx/(width-1) - .5)*wx;
		dcy = cy - ((double)cly/(height-1) - .5)*wy;
		repaint();
	}
	public void mouseReleased(MouseEvent e) {
		parent.setParams(dcx, dcy, dwx);
		temparea = area;
		repaint();
	}
	
	public void mouseDragged(MouseEvent e) {
		dwx = 2*((double)Math.abs(clx-e.getX())/(width-1))*wx;
		dwy = (ratio == 0) ? 2*((double)Math.abs(cly-e.getY())/(height-1))*wy : ratio*dwx;
		repaint();
	}
	public void mouseMoved(MouseEvent e) {}
	
	public void stopped() {
		parent.stopped(this);
	}
	
}
