package org.plenix.jsp.language.ecmascript;

import FESI.jslib.*;
import java.io.*;
import java.util.*;

import org.plenix.jsp.ResourceManager;

public class ESEvaluator
{
  private boolean inUse;
  private JSGlobalObject evaluator;

  protected ESEvaluator(JSGlobalObject prototype, String[] extensions)
    throws JSException, IOException
  {
    this.inUse = false;
    this.evaluator = JSUtil.makeEvaluator(extensions);

    // Copy Variables
    Vector variables = (Vector) prototype.evalAsFunction("getVariables(this)");

    int variableCount = variables.size();
    for (int i = 0; i < variableCount; i++)
    {
      String variableName = (String) variables.elementAt(i);
      this.evaluator.setMember(variableName, prototype.eval(variableName));
    }

    // Copy functions
    this.evaluator.eval((String) prototype.evalAsFunction("getFunctions(this)"));
  }

  protected JSGlobalObject getGlobalObject()
  {
    return this.evaluator;
  }

  protected synchronized boolean acquire()
  {
    if (this.inUse)
    {
      return false;
    }

    this.inUse = true;

    return true;
  }

  protected synchronized void release()
  {
    this.inUse = false;
  }
}
