// (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 EraseAgent extends SpeechAgent
    implements Erase
{
  protected Sketch sketch;
  protected AppGrammar grammar;
  protected Asker ask;

  public EraseAgent( ) throws RemoteException
  {
    System.err.println( "Constructing eraseagent" );
      
    grammar = loadGrammar();
    makeAlwaysActive( grammar );
    
    // get the sketch agent
    sketch = (Sketch)reliesOn( "rec.agent.Sketch" );

    ask = (Asker)reliesOn( "speech.tools.Asker" );

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


  /**
   * Incoming speech goes through here.
   */
  public void acceptedTagsResult (Hashtable tags) throws RemoteException
  {
    if ( tags.containsKey( "erase" ) )
      {
	if ( tags.containsKey( "node" ) )
	  erase( NODE );
	else if ( tags.containsKey( "edge" ) )
	  erase( EDGE );
	else
	 {
	   if ( ask.ask( "Are you sure you want to erase everything?" ) 
	       == Asker.YES )
	    erase( EVERYTHING );
	   else
	     alert( "nothing erased." );
	 }
      }
    else
      System.err.println("Unrecognized utterance in Erase");
  }  



  /**
   * @param what   null means everything, else it switches in its
   *               known classes, and it and all children are nuked.
   */
  public void erase( int what_erase ) throws RemoteException
  {
    final int what = what_erase;

    Gremlin g = new Gremlin( ) {
      int killed = 0;

      public int tweak( Surface surf )
	{
	  killed = 0;
	  Iterator e = surf.getWidgetsIterator();
	  while( e.hasNext() )
	    {
	      if ( what == EVERYTHING )
		kill( surf, (Widget)e.next() );
	      else
		{
		  Widget w = (Widget)e.next();
		  System.err.println( "Analyzing " + w );

		  if ( what == NODE )
		    {
		      if ( w instanceof rec.fsm.Node )
			kill( surf, w );
		    }
		  else if ( what == EDGE )
		    {
		      if ( w instanceof rec.fsm.Edge )
			kill( surf, w );
		    }
		  else
		    System.err.println(
                            "Unrecognized widget removal id " + w );
		}
	    }
	
	  System.err.println( "Killed " + killed + " objects." );
	  return killed;
	}

      private void kill( Surface surf, Widget w )
	{
	  if ( killed == 0 )
	    surf.beginEvent();

	  killed++;
	  surf.removeWidget( w );
	}
    };

    sketch.takeGremlin( g );
  }


}



