<%@ page language="java" %>
<%@ page import="gov.vha.edb.rules.repository.EDBRepository" %>
<%@ page import="gov.vha.edb.rules.web.SessionListener" %>
<%@ page import="gov.vha.edb.rules.web.builder.WebBuilder" %>
<%@ page import="ilog.rules.repository.model.IlrRepository" %>
<%@ page import="ilog.rules.repository.model.IlrRefPackage" %>
<%@ page import="ilog.rules.repository.model.IlrRepException" %>
<%@ page import="ilog.rules.repository.facility.IlrPersistenceManager" %>
<%@ page import="ilog.rules.repository.facility.IlrPersistenceHandler" %>
<%@ page import="ilog.rules.repository.facility.IlrFilePersistenceHandler" %>
<%@ page import="ilog.rules.repository.brm.IlrBrmRepository" %>
<%@ page import="ilog.rules.repository.brm.IlrBrmConstants" %>
<%@ page import="ilog.rules.repository.brm.IlrProject" %>
<%@ page import="ilog.rules.repository.brm.IlrBrmDeployer" %>
<%@ page import="java.util.Iterator" %>

<%
  WebBuilder builder = WebBuilder.getInstance(request);
  //String rootDir = request.getParameter("rootDir");
  //IlrRepository rep = new IlrBrmRepository();
  String rootDir =  session.getServletContext().getInitParameter("repository.dir");
  EDBRepository rep = new EDBRepository();
  rep.setClassLoader(this.getClass().getClassLoader());
  IlrPersistenceManager pmgr = rep.getPersistenceManager();
  IlrPersistenceHandler phandler
    = new IlrFilePersistenceHandler(rep, rootDir);
  rep.setPersistenceHandler(phandler);
  try {
    phandler.open();
    SessionListener.register(session, rep);
    pmgr.loadRepository(false);
  } catch (IlrRepException e) {
    throw new ServletException(e);
  }
  builder.setCurrentRepository(rep);
  String projectName = request.getParameter("project");
  IlrProject project = null;
  if (projectName!=null) {
    project = (IlrProject)rep.findElement(projectName);
  }
  if (project==null) {
    Iterator it = rep.content();
    while (it.hasNext()) {
      Object obj = it.next();
      if (obj instanceof IlrProject) {
        project = (IlrProject)obj;
        break;
      }
    }
  }
  if (project==null) {
    // Creates a project.
    project = IlrProject.createProject(rep.getDefaultExtent());
  }
  
  // this insures that the reflect used internally (conversion, checks, ...) 
  // will know classes in the war (IlrContext required)
  // Beware that the XOM classes have also to be added in the war or server classpath
  IlrBrmDeployer deployer = (IlrBrmDeployer) project.getDeployer();
  deployer.getXOM().getReflect().setClassLoader(this.getClass().getClassLoader());
 
  builder.setCurrentProject(project);
  response.sendRedirect(request.getContextPath()+"/jsp/main.jsp");
%>
