package org.nfunk.jep;

import java.util.Enumeration;
import java.util.Hashtable;

public class SymbolTable extends Hashtable {
  protected VariableFactory vf;
  
  public SymbolTable(VariableFactory paramVariableFactory) {
    this.vf = paramVariableFactory;
  }
  
  private SymbolTable() {}
  
  public Object get(Object paramObject) {
    return getValue(paramObject);
  }
  
  public Object getValue(Object paramObject) {
    Variable variable = super.get(paramObject);
    return (variable == null) ? null : variable.getValue();
  }
  
  public Variable getVar(String paramString) {
    return super.get(paramString);
  }
  
  public Object put(Object paramObject1, Object paramObject2) {
    return makeVarIfNeeded((String)paramObject1, paramObject2);
  }
  
  public boolean setVarValue(String paramString, Object paramObject) {
    Variable variable = super.get(paramString);
    return (variable != null) ? variable.setValue(paramObject) : false;
  }
  
  public Variable addVariable(String paramString, Object paramObject) {
    Variable variable = super.get(paramString);
    if (variable != null)
      return null; 
    variable = this.vf.createVariable(paramString, paramObject);
    super.put(paramString, variable);
    variable.setValidValue(true);
    return variable;
  }
  
  public Variable addConstant(String paramString, Object paramObject) {
    Variable variable = addVariable(paramString, paramObject);
    if (variable != null)
      variable.setIsConstant(true); 
    return variable;
  }
  
  public Variable makeVarIfNeeded(String paramString, Object paramObject) {
    Variable variable = super.get(paramString);
    if (variable != null) {
      variable.setValue(paramObject);
      return variable;
    } 
    variable = this.vf.createVariable(paramString, paramObject);
    super.put(paramString, variable);
    return variable;
  }
  
  public Variable makeVarIfNeeded(String paramString) {
    Variable variable = super.get(paramString);
    if (variable != null)
      return variable; 
    variable = this.vf.createVariable(paramString, null);
    super.put(paramString, variable);
    return variable;
  }
  
  public String toString() {
    StringBuffer stringBuffer = new StringBuffer();
    Enumeration enumeration = elements();
    while (enumeration.hasMoreElements()) {
      Variable variable = (Variable)enumeration.nextElement();
      stringBuffer.append(variable.toString());
      stringBuffer.append("\n");
    } 
    return stringBuffer.toString();
  }
  
  public void clearValues() {
    Enumeration enumeration = elements();
    while (enumeration.hasMoreElements()) {
      Variable variable = (Variable)enumeration.nextElement();
      if (!variable.isConstant())
        variable.setValidValue(false); 
    } 
  }
  
  public VariableFactory getVariableFactory() {
    return this.vf;
  }
}
