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

package rec.fsm.speech;

import rec.agent.*;




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


public class NodeCounterAgent extends SpeechAgent
    implements NodeCounter, ModuleListener
{
  Sketch sketch;

  int numNodes;
  ModuleListener nodeListener;
  RemoteModule nodeModule;

  public NodeCounterAgent( ) throws RemoteException
  {
    try {
      System.err.println( "Constructing nodeagent" );
    AppGrammar g = loadGrammar();
    makeAlwaysActive( g );
    
    /*
    // no stub making so this is broken
    nodeListener = new ModuleListener( ) {
    };
    */
    nodeListener = this;

    // get the sketch agent
    sketch = (Sketch)reliesOn( "rec.agent.Sketch" );

    System.err.println( "Constructing nodeagent -- sketch relied on" );
    ModuleMaker mm = new ModuleMaker( "rec.fsm.speech.NodeCounterModule" );

    System.err.println( "Constructing nodeagent -- module made" );
    nodeModule = sketch.installModule( mm, nodeListener );
    
    System.err.println( "Constructing nodeagent -- module installed" );
    
    } catch ( Throwable th )
      {
	th.printStackTrace();
	System.exit( 1 );
      }
  }

  /**
   * THIS IS THE MODULELISTENER PART
   *
   * This should really be in a seperate class.  Inline code doesn't work
   * due to the need for stubs, etc.
   */
      public Object ring( Object o )
	{
	  numNodes = ( (Integer)o ).intValue();

	  System.err.println( "I know we have " + numNodes + " nodes now!" );
	  return null;
	}

  /**
   * Incoming speech goes through here.
   */
  public void acceptedTagsResult (Hashtable tags) throws RemoteException
  {
    if ( tags.containsKey( "ask" ) )
      {
	int num = numNodes();
	
	alert( "There are " + num + " nodes, last I heard." );
      }
    else
      System.err.println("Unrecognized utterance in speech.tools.NodeCounter");
  }  

  public int numNodes( ) throws RemoteException
  {
    return numNodes;
  }




}



