// DirectoryResource.java
// $Id: CounterCommand.java,v 1.3 1997/07/08 07:01:19 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 w3c.www.http.*;
import w3c.jigsaw.http.*;
import w3c.jigsaw.resources.*;
import w3c.util.*;


/**
 * Implementation of the SSI <code>counter</code> command.  
 * Used to do things like cpt = cpt + 1.
 * @author Benoit Mahe <bmahe@sophia.inria.fr>
 */
public class CounterCommand implements Command {
  private final static String  NAME  = "cpt";
  private final static boolean debug = true;

  private static final String keys[] = {
    "name",
    "init",
    "incr",
    "value"
  };

  protected final int defaultinit = 0;

  public String getName() {
    return NAME;
  }


  public String getValue(Dictionary variables, String var) {
    return String.valueOf(getCounterValue(variables, var));
  }

  protected void initCounterValue(Dictionary d, String name, String value) {
    d.put(getClass().getName()+"."+name, new Integer(value));
  }

  protected void changeCounterValue(Dictionary d, String name, String incr) {
    int change       = (Integer.valueOf(incr)).intValue();
    int value = getCounterValue(d,name) + change;
    d.put(getClass().getName()+"."+name, new Integer(value));
  }

  protected int getCounterValue(Dictionary d, String name) {
    Integer value = (Integer)d.get(getClass().getName()+"."+name);
    if (value != null) 
      return value.intValue();
    else 
      return defaultinit;
  }

  public Reply execute(SSIResource resource
		       , Request request
		       , ArrayDictionary parameters
		       , Dictionary variables) {
    Object values[] = parameters.getMany(keys);
    String name     = (String) values[0];
    String init     = (String) values[1];
    String incr     = (String) values[2];
    String value     = (String) values[3];
    String text     = null;
    if (name != null) {
      if (init != null)
	initCounterValue(variables,name,init);
      if (incr != null) {
	changeCounterValue(variables,name,incr);
      }
      if (value != null) {
	text = String.valueOf(getCounterValue(variables,name));
      }
    }
    Reply reply = resource.createCommandReply(request, HTTP.OK);
    if (text != null)
      reply.setContent(text);
    return reply;
  }

}
