import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.undo.*;

/**
 * A fairly generic undo/redo action that can be added to
 * menus and toolbars.
 *
 * It changes its state when an edit occurs and when
 * an undo/redo occurs.
 *
 * @version 1.0
 * @author  Prof. David Bernstein, James Madison University
 */
public class UndoRedoAction extends    AbstractAction
			    implements UndoableEditListener
{
    private UndoableEdit      lastEdit;


    /**
     * Default Constructor
     */
    public UndoRedoAction()
    {
	putValue(Action.NAME, "Undo/Redo");
	setEnabled(false);
    }

    /**
     * Perform the action
     */
    public void actionPerformed(ActionEvent evt)
    {
	if (lastEdit != null) 
        {
	    if (lastEdit.canUndo()) 
            {
		lastEdit.undo();
		putValue(Action.NAME, 
			 lastEdit.getRedoPresentationName());
	    } 
            else if (lastEdit.canRedo()) 
            {
		lastEdit.redo();
		putValue(Action.NAME, 
			 lastEdit.getUndoPresentationName());
	    } 
            else 
            {
		putValue(Action.NAME, "Undo/Redo");
		setEnabled(false);
	    }
	}
    }


    /**
     * Handle UndoableEidtHappened events
     * (Required by UndoableEditListener)
     */
    public void undoableEditHappened(UndoableEditEvent evt)
    {
	lastEdit = evt.getEdit();

	if (lastEdit.canUndo()) 
        {
	    putValue(Action.NAME, 
		     lastEdit.getUndoPresentationName());

	    setEnabled(true);
	}
    }
}
