package org.plenix.jsp.language.ecmascript;

import FESI.jslib.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

import org.plenix.jsp.*;
import org.plenix.jsp.language.*;

public class ESProcessor extends LanguageProcessorImpl
{
  String[] extensions = null;

  // Program instance services
  public void init(String path) throws LanguageException
  {
    String extensionList = getParameter("extensions");

    if (extensionList == null)
    {
      extensions = new String[0];
    }
    else
    {
      extensions = Util.split(extensionList, ",");
    }

    String fesiPath = getParameter("fesiPath");

    if (fesiPath != null)
    {
      Properties properties = System.getProperties();
      String initialPath = (String) properties.get("FESI.path");

      if (initialPath == null)
      {
        properties.put("FESI.path", fesiPath);
      }
      else if (initialPath.indexOf(fesiPath) == -1)
      {
        properties.put("FESI.path", initialPath + File.pathSeparator + fesiPath);
      }

      System.setProperties(properties);
    }
  }

  public void unload(Object program) throws LanguageException { }
  public void compile(String baseName, String path) throws LanguageException { }

  public Object load(String baseName, String path)
    throws LanguageException
  {
    ESProgram esProgram = null;
    String fileName = path + File.separator + baseName + "." + getSourceExtension();

    try
    {
      esProgram = new ESProgram(fileName, extensions);
    }
    catch (Exception e)
    {
      throw new LanguageException("Error loading '" + fileName + "': " + e.getMessage());
    }

    return esProgram;
  }


  public void execute(Object program, HttpServletRequest request, HttpServletResponse response)
    throws LanguageException
  {
    ESProgram esProgram = (ESProgram) program;

    try
    {
      esProgram.execute(request, response);
    }
    catch (Exception e)
    {
      throw new LanguageException("Error executing '" + esProgram.getFileName() + "': " + e.getMessage());
    }
  }
}
