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

package rec.fsm.speech;

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

public class EraseSpecificAgent extends EraseAgent
    implements EraseSpecific, ModuleListener
{

  Hashtable names;
  ModuleListener eraseListener;
  RemoteModule eraseModule;

  public EraseSpecificAgent( ) throws RemoteException
  {
    super();

    names = new Hashtable();
    eraseListener = this;

    ModuleMaker mm = new ModuleMaker( "rec.fsm.speech.NameTrackerModule" );
    eraseModule = sketch.installModule( mm, eraseListener );
  }


  /**
   * Incoming speech goes through here.
   */
  public void acceptedTagsResult (Hashtable tags) throws RemoteException
  {
    System.err.println( "Erase specific activated." );
    if ( tags.containsKey( "nerase" ) )
      {
	String name = (String)tags.get( "name" );

	if ( name == null )
	  System.err.println("got null name in Erase");
	else
	  erase( NODE, name );
      }
    else
      super.acceptedTagsResult( tags );
  }  



  /**
   * @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, String what_name ) throws RemoteException
  {
    final int what = what_erase;
    final String name = what_name;

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

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

	      if ( what == NODE )
		{
		  if ( ( w instanceof rec.fsm.Node )
		       && ( name.equals( ((rec.fsm.Node)w).getName() ) ) )
		    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++;
	  if ( w instanceof Node )
	    NodeRemover.removeNode( surf, (Node)w );
	  else
	    surf.removeWidget( w );
	}
    };

    sketch.takeGremlin( g );
  }


  public Object ring( Object o ) throws RemoteException
  {
    NameTracker n = (NameTracker)o;
    
    if ( n.added )
      {
	if ( names.get( n.name ) == null )
	  {
	    if ( n.name.length() < 10 )
	      grammar.addAlternative( "name", n.name );
	    names.put( n.name, n.name );
	  }
      }
    else
      {
	names.remove( n.name );
	System.err.println( "Not able to remove alternative." );
      }
    System.err.println( "I know we have " + names.keys() + " names now!" );
    
    return null;
  }
  
  
}



