// (c) MIT 2003.  All rights reserved.

package rec.agent;




import java.rmi.*;
import java.util.*;
import speech.*;
import speech.tools.*;
import metaglue.*;
import rec.sys.*;

public class UndoAgent extends SpeechAgent
    implements Undo
{
  Sketch sketch;

  public UndoAgent( ) throws RemoteException
  {
    System.err.println( "Constructing undoagent" );
      
    AppGrammar g = loadGrammar();
    makeAlwaysActive( g );
    
    // get the sketch agent
    sketch = (Sketch)reliesOn( "rec.agent.Sketch" );

    //    alert( "Undo agent up and running." );
  }


  /**
   * Incoming speech goes through here.
   */
  public void acceptedTagsResult (Hashtable tags) throws RemoteException
  {
    if ( tags.containsKey( "undo" ) )
      undo( false, false );
    else if ( tags.containsKey( "redo" ) )
      undo( true, false );
    else if ( tags.containsKey( "toggle" ) )
      undo( false, true );
    else
      System.err.println("Unrecognized utterance in Undo");
  }  



  /**
   * @param what   null means everything, else it switches in its
   *               known classes, and it and all children are nuked.
   */
  public void undo( boolean redo, boolean rec_event ) throws RemoteException
  {
    final boolean r = redo;
    final boolean asevent = rec_event;
    Gremlin g = new Gremlin( ) {

      public int tweak( Surface surf )
	{
	  if ( r ) 
	    surf.redo();
	  else
	    surf.undo();

	  //	  if ( asevent )
	  //    surf.beginEvent(); // record this so next undo undoes this one.

	  return 0;
	}
    };

    sketch.takeGremlin( g );
  }


  public void undo() throws RemoteException
  {
    undo( false, false );
  }

  public void redo() throws RemoteException
  {
    undo( true, false );
  }
}




