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

package rec.fsm.speech;

import rec.agent.*;




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


public class NodeCounterModule extends RemoteModuleImpl
    implements Registerable
{
  
  Hashtable nodes;

  public NodeCounterModule( ModuleListener parent ) throws RemoteException
  {
    super( parent );
    
    nodes = new Hashtable();

    System.err.println( "Constructed NodeCounter connected to " + parent );
  }


  public boolean recognizeWidget( Surface s, Widget w )
  {
    if ( w instanceof rec.fsm.Node )
      {
	if ( ! nodes.containsKey( w ) )
	  {
	    nodes.put( w, w );
	    s.register( this, w );

	    // we got a circle!
	    tellPop( true );
	  }
      }

    return false;
  }  


  private void tellPop( boolean new_one )
  {
    try 
      {
	System.err.println( "Telling pop " + new_one );
	Integer b = new Integer( nodes.size() );
	parent.ring( b );
      }
    catch ( RemoteException e )
      {
	e.printStackTrace();
      }
  }

  public void removed( Widget w )
  {
    //Console.writeln( "Seeing thing disappear." );
    nodes.remove( w );
    tellPop( false );
  }

  public void replaced( Widget ow, Widget nw )
  {
    nodes.remove( ow );
    if ( nw instanceof rec.fsm.Node )
      {
	nodes.put( nw, nw );
      }
    else
      {
	tellPop( false );
      }
  }

  public void replaced( Widget ow, Collection nws )
  {
    Iterator it = nws.iterator();
    while( it.hasNext() )
      replaced( ow, (Widget)it.next() );
  }


  public void altered( Widget w, Transition t )
  {
  }

}
