package sim.util;

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

public class StickyLightButtonListener extends MouseAdapter implements MouseMotionListener
{
    private boolean buttonUpOnLastMouseDown = true;
	
	public void activate(LightButton lb)
	{
		lb.setArmed(false);
		lb.processActionEvent();
	}
	
	public void arm(LightButton lb)
	{
		lb.setArmed(true);
	}
	
	public void disarm(LightButton lb)
	{ 
		lb.setArmed(false);
	}
	
    public void mousePressed(MouseEvent event)
	{
		LightButton lb = (LightButton)event.getSource();
		if(lb.isEnabled())
		{
        	if(lb.isRaised())
				lb.setInset();
        	else
				lb.setRaised();
			
        	this.buttonUpOnLastMouseDown = lb.isRaised();
			this.arm(lb);
		}
    }
	
	public void mouseClicked(MouseEvent event)
	{
		LightButton lb = (LightButton)event.getSource();
		
		if(lb.isEnabled() && lb.isArmed())
			this.activate(lb);
	}
	
	public void mouseReleased(MouseEvent event)
	{
		LightButton lb = (LightButton)event.getSource();
		Point pt = event.getPoint();
		
		if(lb.contains(pt.x, pt.y))
			this.mouseClicked(event);
	}
	
    public void mouseDragged(MouseEvent event)
	{
		LightButton lb = (LightButton)event.getSource();
		if(lb.isEnabled())
		{
			Point loc = event.getPoint();

        	if(lb.contains(loc.x,loc.y))
			{
        	    if(this.buttonUpOnLastMouseDown)
				{
        	        if(!lb.isRaised()) 
						lb.setRaised();
        	    }
        	    else 
        	        if(lb.isRaised())
						lb.setInset();
        	}
        	else {
        	    if(buttonUpOnLastMouseDown)
				{
        	        if(lb.isRaised())
						lb.setInset();
				}
        		else 
        			if(!lb.isRaised())
						lb.setRaised();
        	}
    	}
	}
	
	public void mouseMoved(MouseEvent event)
	{
	}
}