// BasicCommandRegistry.java
// $Id: BasicCommandRegistry.java,v 1.10 1997/06/17 13:08:31 bmahe Exp $
// (c) COPYRIGHT MIT and INRIA, 1996.
// Please first read the full copyright statement in file COPYRIGHT.html

package w3c.jigsaw.ssi ;

import java.util.* ;
import java.io.* ;

import w3c.www.http.HTTP ;
import w3c.util.* ;
import w3c.jigsaw.resources.* ;
import w3c.jigsaw.http.* ;

/**
 * An implementation of CommandRegistry that uses a hash table
 * to store the commands.
 * @author Antonio Ramirez <anto@mit.edu>
 */
public class BasicCommandRegistry extends CommandRegistry
{
    
    Hashtable /*<String,Command>*/ commands = null ;

    public BasicCommandRegistry()
    {
	commands = new Hashtable(23) ;
    }

    public void registerCommand(Command cmd)
    {
	commands.put( cmd.getName().toLowerCase(),
		      SSIResource.debug
		      ? new DebugWrapperCommand(cmd)
		      : cmd ) ;
    }

    public Command lookupCommand(String name)
    {
	Command cmd = (Command)
	    commands.get(name.toLowerCase()) ;
	if(cmd != null) return cmd ;
	else return new DefaultCommand(name) ;
    }

    public Dictionary initVariables(SSIResource resource,
				    Request request,
				    Dictionary variables)
    {
	return variables ;
    }
}

class DefaultCommand implements Command {
    private String badCommand ;

    DefaultCommand(String badCommand)
    {
	this.badCommand = badCommand ;
    }

    public String getName()
    {
	return null ;
    }
    
    public Reply execute(SSIResource resource,
			 Request request,
			 ArrayDictionary parameters,
			 Dictionary variables)
    {
	Reply reply =
	    resource.createCommandReply(request,HTTP.OK) ;

	reply.setContent("[SSIResource: unknown command \""+badCommand+"\"]");
	
	return reply ;
    }

    public boolean modifiedSince(long date,
				 SSIResource resource,
				 Request request,
				 ArrayDictionary parameters,
				 Dictionary variables)
    {
	return false;
    }

  public String getValue(Dictionary variables, String variable) {
    return "null";
  }

}

class DebugWrapperCommand implements Command {

    Command cmd ;

    public DebugWrapperCommand(Command cmd)
    {
	this.cmd = cmd ;
	System.out.println("@@@@ Added command: "+cmd.getName()) ;
    }

    public final Reply execute(SSIResource resource,
			       Request request,
			       ArrayDictionary parameters,
			       Dictionary variables)
    {
	System.out.println("@@@@ Executing command: "+cmd.getName()+
			   " "+parameters) ;
	return cmd.execute(resource,request,parameters,variables) ;
    }
			 
    public final String getName()
    {
	return cmd.getName() ;
    }

  public String getValue(Dictionary variables, String variable) {
    return "null";
  }

}





