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

import gjt.*;

/**
  * this class moves a figure, the ideas are from <em>Graphic Java,
  * Mastering the AWT</em>, by David Geary, second edition, in
  * particular see the DoubleBufferedContainer example and the class
  * LightweightDragger on page 497
  *
  * @author Owen Astrachan
  */

public class MoveTool extends ToolAdapter
{
    public MoveTool(Controller c)
    {
	super(c);
    }

    public void setActive(boolean status)
    {
	if (status == true)
	{
	    myController.getDrawingArea().addMouseListener(this);
	    myController.getDrawingArea().addMouseMotionListener(this);
	}
	else
	{
	    myController.getDrawingArea().removeMouseListener(this);
	    myController.getDrawingArea().removeMouseMotionListener(this);
	}
    }

    public void mousePressed(MouseEvent e)
    {
	myLast = new Point(e.getX(), e.getY());
	myFigure = myController.getFigure(myLast);
	myIsDragging = true;
    }
    
    public void mouseReleased(MouseEvent e)
    {
	myIsDragging = false;
    }

    public void mouseClicked(MouseEvent e)
    {
	myIsDragging = false;
    }

    public void mouseDragged(MouseEvent e)
    {
	if (myIsDragging && myFigure != null)
	{
	    Point loc = myFigure.getLocation();
	    Point nextLoc = new Point(
		loc.x + e.getX() - myLast.x,
		loc.y + e.getY() - myLast.y);

	    Rectangle bounds = myFigure.getBounds();
	    myFigure.setLocation(nextLoc);
	    bounds.add(myFigure.getBounds());
	    
	    // why is this here, needed in 1.1.5, not in 1.1.3 ?
	    // this is repainting based on a clip of damaged region
	    
	    myFigure.getParent().repaint(bounds.x,bounds.y,
					 bounds.width,bounds.height);
	    
	    myLast.x = e.getX();
	    myLast.y = e.getY();
	}
    }
    
    private boolean myIsDragging = false;
    private Point myLast;
    private Figure myFigure;
}
