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

package rec.fsm.speech;

import rec.agent.*;

import java.rmi.*;
import java.util.*;
import speech.*;
import metaglue.*;
import rec.agent.*;
import rec.ui.*;
import rec.util.*;
import rec.sys.*;

public class RunFSMAgent extends TalkAgent
    implements RunFSM
{
  boolean loadedFSM = false;
  Id fsm_Id = null;

  AppGrammar stopgrammar = null;

  public RunFSMAgent( ) throws RemoteException
  {
    stopgrammar = loadGrammar( "rec.fsm.speech.StopFSM" );
    makeAlwaysActive( stopgrammar );
    stopgrammar.deactivate();
  }


  /**
   * Incoming speech goes through here.
   */
  public void acceptedTagsResult (Hashtable tags) throws RemoteException
  {
    if ( tags.containsKey( "runFSM" ) )
      {
	alert( "okay" );
	runFSM();
	alert( "ready to draw" );
      }

    else if ( tags.containsKey( "stopFSM" ) )
      {
	removeFSM();
	alert( "f s m recognition stopped." );
      }
    else
      error( "do not recognize utterance." );
  }

  
  public void runFSM( ) throws RemoteException
  {
    if ( loadedFSM )
      return;
  
    loadedFSM = true;
    
    // install the FSM module
    System.err.println( "Installing FSM Module." );
    fsm_Id = sketch.installModule( new ModuleMaker( ) {
      public Module make( Object parent )
	{
	  try 
	    {
	      RecIniFile f = new RecIniFile( "fsm.mod" );
	      return f.getModule();
	    }
	  catch ( Exception e )
	    {
	      e.printStackTrace();
	      System.err.println( "....making FSM module failed...." );
	    }

	  return null;
	}
    }
     );

    // now fix grammars
    grammar.deactivate();
    stopgrammar.activate();

    System.err.println( "Done installing FSM Module." );
  }

  public void removeFSM( ) throws RemoteException
  {
    if ( loadedFSM )
    {
      sketch.removeModule( fsm_Id );
      loadedFSM = false;
      
      stopgrammar.deactivate();
      grammar.activate();
    }
    else
      System.err.println( "can not remove FSM module--not installed." );
  }

} // end RunFSMAgent



