/********************************************************************
 * Copyright © 2004 EDS. All rights reserved
 ********************************************************************/
package gov.vha.edb.rules.web.builder;

import ilog.rules.repository.brm.*;
import ilog.rules.repository.event.*;
import ilog.rules.repository.facility.*;
import ilog.rules.repository.model.*;
import ilog.rules.util.logging.*;
import ilog.rules.webui.*;
import ilog.webui.dhtml.*;
import ilog.webui.dhtml.components.*;

import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.commons.io.IOUtils;


import java.io.*;
import java.lang.reflect.*;
import java.text.*;
import java.util.*;

public class WebBuilder extends IlxWComponent
{
  private static final long serialVersionUID = 3988256773033890015L;
  public static final int PROPERTIES_CENTER = 0;
  public static final int PROPERTIES_EAST = 1;

  private ExplorerPanel explorerPanel;
  private CenterPanel centerPanel;
  private PropertyPanel propertyPanel;
  private MessagePanel messagePanel;
  private IlxWPanel dtableEditPanel;

  private IlxWMenuBar menuBar;
  private WebAction.Map actionMap;

  private IlxWMenu addRuleMenu;
  private IlxWMenu openProjectMenu;

  private int propertiesPlacement = PROPERTIES_CENTER;

  private IlrElement editedElement;
  private IlrPackage currentPackage;
  private IlrProject currentProject;
  private IlrRefPackage currentExtent;
  private IlrBrmRule currentRuleTemplate;

  protected Logger logger;
  private Clipboard clipboard = new Clipboard();

  public String exitPath = "/startup/exit.jsp";

  private Locale locale;
  private IlxWLabel elementLabel;
  private IlxWLabel projectLabel;
  
  private ClientProperties clientProperties;

    public WebBuilder(Locale locale)
    {
      this.locale = locale;
      actionMap = BuilderActions.makeActionMap();

      // For filling the actionMap.
      getMenuBar();
      add(actionMap.getActionHolder());
      Logger parentLogger = Logger.getLogger("ilog.rules",
                                             "ilog.rules.util.prefs.IlrLoggerMessages");
      parentLogger.setLevel(Level.ALL);
      ConsoleHandler handler = new ConsoleHandler();
      handler.setLevel(Level.ALL);
      projectLabel = new IlxWLabel();
      add(projectLabel);
      elementLabel = new IlxWLabel();
      add(elementLabel);

      // Enable traces here.
//    IlxWConfig.traceEnabled = true;
//    IlxWConfig.benchClient = true;
//    IlxWConfig.benchService = true;
//    IlxWConfig.testSerialization_SaveAttributes = true;
//    IlxWConfig.testSerialization_ReloadAttributes = true;
//    IlxWConfig.testSerialization_TmpFile = "/tmp/test_serial";

    }

  public void setExitPath(String exitPath)
  {
    this.exitPath = exitPath;
  }

  public int getPropertiesPlacement()
  {
    return propertiesPlacement;
  }

  public void setPropertiesPlacement(int placement)
  {
    propertiesPlacement = placement;
    getPropertyPanel().configureLayout();
    getCenterPanel().configureLayout();
    IlxWPort port = IlxWPort.getCurrentPort();
    if (port != null) {
      port.invalidatePage();
    }
    updateActionStates();
  }

  public WebAction.Map getActionMap()
  {
    return actionMap;
  }

  protected void printComponent(IlxWPort port) throws IOException
  {
    // Do nothing.
  }

  public static WebBuilder getInstance(HttpServletRequest request)
  {
    HttpSession session = request.getSession();

    final String id = "web.builder.instance";
    IlxWManager manager = IlxWManager.getManager(session);
    WebBuilder builder
        = (WebBuilder) manager.getComponentNamed(id);
    if (builder == null) {
      Locale loc;
      String locale = request.getParameter("locale");
      if (locale != null) {
        StringTokenizer stk = new StringTokenizer(locale, "_");
        String language = stk.nextToken();
        String country = stk.nextToken();
        String variant = "";
        while (stk.hasMoreTokens()) {
          variant += stk.nextToken();
          if (stk.hasMoreTokens()) {
            variant += '_';
          }
        }
        if ("".equals(variant)) {
          loc = new Locale(language, country);
        } else {
          loc = new Locale(language, country, variant);
        }
        session.setAttribute("web.builder.locale", loc);
      } else {
        loc = request.getLocale();
        session.setAttribute("web.builder.locale", loc);
      }
      builder = new WebBuilder(loc);
      manager.add(builder);
      builder.setName(id);
    }
    return builder;
  }

  public Locale getLocale()
  {
    return locale;
  }

  public String getMessage(String key)
  {
    String[] args = {};
    return getMessage(key, args);
  }

  public String getMessage(String key,
                           String arg)
  {
    String[] args = {arg};
    return getMessage(key, args);
  }

  public String getMessage(String key,
                           String arg1,
                           String arg2)
  {
    String[] args = {arg1, arg2};
    return getMessage(key, args);
  }

  public String getMessage(String key,
                           String[] args)
  {
    ResourceBundle bundle
        = ResourceBundle.getBundle("gov.vha.edb.rules.web.builder.messages",
                                   this.locale,
                                   WebBuilder.class.getClassLoader());
    String value;
    try {
      value = bundle.getString(key);
    } catch (MissingResourceException e) {
      value = key;
    }
    if (value == null) {
      value = key;
    }
    return MessageFormat.format(value, args);
  }

  private static transient Properties properties;

  public static synchronized String getProperty(String key)
  {
    if (properties == null) {
      properties = new Properties();
      InputStream stream = null;
      try {
        String builderProps = "/gov/vha/edb/rules/web/builder/WebBuilder.properties";
        stream
            = WebBuilder.class.getResourceAsStream(builderProps);
        properties.load(stream);
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
    	  if (stream != null) {
    		  org.apache.commons.io.IOUtils.closeQuietly(stream);
    	  }
      }
    }
    return properties.getProperty(key);
  }

  /**
   * <p>Gets or creates the message panel.
   * Note that this method is synchronized because it can be called
   * from several JSP pages or servlets at the same time.</p>
   */
  public synchronized MessagePanel getMessagePanel()
  {
    if (messagePanel == null) {
      messagePanel = new MessagePanel(this);
      add(messagePanel);
    }
    return messagePanel;
  }

  public IlxWPanel getDtableEditPanel()
  {
    if (dtableEditPanel == null) {
      dtableEditPanel = new IlxWPanel();
      getManager().add(dtableEditPanel);
    }
    return dtableEditPanel;
  }

  /**
   * <p>Gets or creates the definition panel.
   * Note that this method is synchronized because it can be called
   * from several JSP pages or servlets at the same time.</p>
   */
  public synchronized CenterPanel getCenterPanel()
  {
    if (centerPanel == null) {
      centerPanel = new CenterPanel(this);
      add(centerPanel);
    }
    return centerPanel;
  }

  /**
   * <p>Gets or creates the definition panel.
   * Note that this method is synchronized because it can be called
   * from several JSP pages or servlets at the same time.</p>
   */
  public synchronized PropertyPanel getPropertyPanel()
  {
    if (propertyPanel == null) {
      propertyPanel = new PropertyPanel(this);
      add(propertyPanel);
    }
    return propertyPanel;
  }

  /**
   * <p>Gets or creates the explorer panel.
   * Note that this method is synchronized because it can be called
   * from several JSP pages or servlets at the same time.</p>
   */
  public synchronized ExplorerPanel getExplorerPanel()
  {
    if (explorerPanel == null) {
      explorerPanel = new ExplorerPanel(this);
      add(explorerPanel);
    }
    return explorerPanel;
  }

  public WebAction getWebAction(String name)
  {
    return actionMap.getWebAction(name);
  }

  private IlxWMenuItem createMenu(String actionName)
  {
    String value = getProperty(actionName);
    if (value != null) {
      Enumeration actionNames = new StringTokenizer(value, " ");
      String text = getProperty(actionName + ".text");
      IlxWMenu menu = new IlxWMenu(getMessage(text));
      while (actionNames.hasMoreElements()) {
        String name = ((String) actionNames.nextElement()).trim();
        if ("-".equals(name)) {
          menu.addSeparator();
        } else {
          menu.add(createMenu(name));
        }
      }
      return menu;
    } else {
      if (BuilderActions.ACTION_OPENPROJECT.equals(actionName)) {
        return openProjectMenu = new IlxWMenu(getMessage(getProperty(actionName + ".text")));
      }
      WebAction action = null;
      try {
        ClassLoader cl = WebBuilder.class.getClassLoader();
        String className = getProperty(actionName + ".class");
        String params = getProperty(actionName + ".params");
        if (className != null) {
          if (params == null) {
            action = (WebAction) Class.forName(className, true, cl).newInstance();
          } else {
            Enumeration parameters = new StringTokenizer(params, " ");
            Vector paramValuesVector = new Vector();
            while (parameters.hasMoreElements()) {
              paramValuesVector.addElement(((String) parameters.nextElement()).trim());
            }
            Class[] ctorParams = new Class[paramValuesVector.size()];
            String[] paramValues = new String[paramValuesVector.size()];
            for (int i = 0; i < paramValuesVector.size(); i++) {
              ctorParams[i] = String.class;
              paramValues[i] = (String) paramValuesVector.elementAt(i);
            }
            Constructor ctor = Class.forName(className, true, cl).getConstructor(ctorParams);
            action = (WebAction) ctor.newInstance(paramValues);
          }
        }
        actionMap.registerWebAction(action);
      } catch (Exception ex) {
        ex.printStackTrace();
      }
      if (BuilderActions.ACTION_CHOOSENEWRULEMODEL.equals(actionName)) {
        return addRuleMenu = (action != null) ? (IlxWMenu) action.makeMenuItem(this) : null;
      }
      return (action != null) ? action.makeMenuItem(this) : null;
    }
  }

  /**
   * <p>Gets or creates the menu bar.
   * Note that this method is synchronized because it can be called
   * from several JSP pages or servlets at the same time.</p>
   */
  public synchronized IlxWMenuBar getMenuBar()
  {
    if (menuBar == null) {
      menuBar = new IlxWMenuBar();
      add(menuBar);
      String value = getProperty("WebBuilder.menubar");
      Enumeration actionNames = new StringTokenizer(value, " ");
      while (actionNames.hasMoreElements()) {
        menuBar.add(createMenu((String) actionNames.nextElement()));
      }
    }
    return menuBar;
  }

  // --- Current package ----------------------------------------------

  public IlrPackage getCurrentPackage()
  {
    return currentPackage;
  }

  public void setCurrentPackage(IlrPackage pckge)
  {
    IlrPackage oldValue = currentPackage;
    if (oldValue != pckge) {
      currentPackage = pckge;
    }
  }

  public void setCurrentPackage(IlrElement object)
  {
    IlrPackage found = null;
    if (object != null) {
      if (object instanceof IlrPackage) {
        found = (IlrPackage) object;
      } else if (object instanceof IlrModelElement) {
        IlrPackage p = ((IlrModelElement) object).getPackage();
        if (p != null) {
          found = p;
        }
      }
    }
    if (found != null) {
      IlrProject project = IlrBrmHelper.getProject(found);
      if (project != null) {
        IlrDeployer deployer = project.getDeployer();
        if (deployer != null) {
          deployer.setCurrentProject(project);
          deployer.setCurrentPackage(found);
        }
      }
    }
    setCurrentPackage(found);
  }

  public IlrProject getCurrentProject()
  {
    return this.currentProject;
  }

  public IlrRepository getCurrentRepository()
  {
    return currentExtent.getRepository();
  }

  public IlrRefPackage getCurrentExtent()
  {
    return currentExtent;
  }

  // Update the Open Project menu if a project is renamed or removed.
  class ProjectUpdater implements ElementListener, Serializable
  {
    private static final long serialVersionUID = -8766743594017734878L;

    public void featureChanged(FeatureChangeEvent e)
    {
      String fName = e.getStructuralFeature().getName();
      if (e.getElement() instanceof IlrProject
          && IlrConstants.NAME_PROPERTY.equals(fName)) {
        updateOpenProjectMenu();
      } /*else {
           WebAction webAction = actionMap.getWebAction(BuilderActions.ACTION_SAVEREPOSITORY);
           webAction.setEnabled(webAction.isEnabled(WebBuilder.this));
         }*/
    }

    public void structureChanged(EventObject e)
    {
    }

    public void elementRemoved(ElementRemoveEvent e)
    {
      if (e.getElement() instanceof IlrProject) {
        updateOpenProjectMenu();
      }
    }
  }

  // Update the Open Project menu list if a project is created.
  class ProjectUpdater2 implements InstanceListener, Serializable
  {
    private static final long serialVersionUID = -349100379930460438L;

    public void elementCreated(InstanceEvent e)
    {
      if (e.getInstance() instanceof IlrProject) {
        updateOpenProjectMenu();
      }
    }
  }

  private ElementListener openProjectMenuUpdater = new ProjectUpdater();

  public void setRepository(HttpServletRequest request)
  {
    String rootDir = request.getParameter("rootDir");
    HttpSession session = request.getSession();
    IlrRepository rep
        = (IlrRepository) session.getAttribute("web.builder.Repository");
    IlrPersistenceManager pmgr;
    IlrFilePersistenceHandler phandler = null;
    Iterator it;
    if (rep == null) {
      rep = new IlrBrmRepository();
      session.setAttribute("web.builder.Repository", rep);
      pmgr = rep.getPersistenceManager();
      phandler = new IlrFilePersistenceHandler(rep);
      pmgr.addPersistenceHandler(phandler);
    } else {
      pmgr = rep.getPersistenceManager();
      it = pmgr.getPersistenceHandlers();
      if (it.hasNext()) {
        phandler = ((IlrFilePersistenceHandler) it.next());
      }
    }
    if (rootDir != null
        && phandler != null
        && !rootDir.equals(phandler.getRootDir())) {
      phandler.setRootDir(rootDir);
      try {
        pmgr.loadRepository(false);
      } catch (IlrRepException e) {
        e.printStackTrace();
      }
    }
    setCurrentExtent(rep.getDefaultExtent());
  }

  public void setCurrentRepository(IlrRepository rep)
  {
    setCurrentExtent(rep.getDefaultExtent());
  }

  public void setCurrentExtent(IlrRefPackage extent)
  {
    this.currentExtent = extent;
    extent.addElementListener(openProjectMenuUpdater);
    extent.addInstanceListener(new ProjectUpdater2());
    extent.getRepository().addPermissionManager(new IlrReadOnlyLibraryPermissionManager());
    extent.getRepository().setLocale(locale);
    updateOpenProjectMenu();
    String sharingMsg =
        extent.getRepository().getPersistenceManager().getLockManager().getRepositorySharingErrorMsg();
    if (sharingMsg != null) {
      getMessagePanel().getMessageList().addAlert(sharingMsg);
    }
  }

  public void setProject(HttpServletRequest request)
  {
    setRepository(request);
    IlrRefPackage refPack = getCurrentExtent();
    if (refPack != null) {
      IlrProject project = null;
      String projectName = request.getParameter("project");
      if (projectName != null) {
        project = (IlrProject) refPack.findModelElement(projectName);
      } else {
        Iterator it = refPack.getRepository().content();
        while (it.hasNext()) {
          Object obj = it.next();
          if (obj instanceof IlrProject) {
            project = (IlrProject) obj;
            break;
          }
        }
        if (project == null) {
          // Create a project.
          project = IlrProject.createProject(refPack);
        }
      }
      setCurrentProject(project);
    }
  }

  public void setCurrentProject(IlrProject project)
  {
    IlrProject oldValue = currentProject;
    if (oldValue != project) {
      this.currentProject = project;
      // Fix BR#2003.1437.
      // Load all libraries & BOM.
      Iterator libs = project.allLibraries();
      while (libs.hasNext()) {
        IlrLibrary library = (IlrLibrary) libs.next();
        IlrBOM bom = library.getBOM();
        bom.loadAll();
      }
      getExplorerPanel().setProject(project);
      getExplorerPanel().setCurrentView(IlrWRepExplorer.PROJECT_TREE_VIEW);
      setEditedElement(null);
      updateCurrentRuleTemplate();
      updateAddRuleMenu();
      updateActionStates();
      projectLabel.setText("Project " + project.getName());
    }
  }

  public void setEditedElement(IlrElement element)
  {
    this.editedElement = element;
    setCurrentPackage(element);
    getCenterPanel().setElement(element);
    getPropertyPanel().setElement(element);
    updateActionStates();
    if (element instanceof IlrModelElement) {
      elementLabel.setText(((IlrModelElement) element).getName());
    }
  }

  public IlrElement getEditedElement()
  {
    return editedElement;
  }

  public IlxWLabel getElementLabel()
  {
    return elementLabel;
  }

  public IlxWLabel getProjectLabel()
  {
    return projectLabel;
  }

  static class Clipboard implements Serializable
  {
    private static final long serialVersionUID = -3258019538834705743L;
    IlrElement copiedElement = null;
    boolean cutting = false;

    public void clear()
    {
      cutting = false;
      copiedElement = null;
    }
  }

  public boolean isElementCut(IlrElement element)
  {
    return (element == clipboard.copiedElement) && clipboard.cutting;
  }

  public void cut()
  {
    if (editedElement != null) {
      if (clipboard.cutting) {
        getExplorerPanel().repaintItem(clipboard.copiedElement);
      }
      clipboard.copiedElement = editedElement;
      clipboard.cutting = true;
      getExplorerPanel().repaintItem(clipboard.copiedElement);
      updateActionState(getWebAction(BuilderActions.ACTION_PASTE));
    }
  }

  public void copy()
  {
    if (editedElement != null) {
      if (clipboard.cutting) {
        getExplorerPanel().repaintItem(clipboard.copiedElement);
      }
      clipboard.copiedElement = editedElement;
      clipboard.cutting = false;
      updateActionState(getWebAction(BuilderActions.ACTION_PASTE));
    }
  }

  public void paste()
  {
    if (clipboard.copiedElement != null) {
      IlrPackage pack = getCurrentPackage();
      IlrProject prj = getCurrentProject();
      IlrModelElement elt = (IlrModelElement) clipboard.copiedElement;

      if (clipboard.cutting) {
        if (pack == elt.getNamespace()) { // If the object does not move.
          clipboard.cutting = false;
          getExplorerPanel().repaintItem(clipboard.copiedElement);
          return;
        }
      } else {
        try {
          elt = (IlrModelElement) elt.clone();
        } catch (CloneNotSupportedException e) {
          e.printStackTrace();
        }
      }
      if (pack != prj) {
        pack.addContent(elt, true);
      } else {
        //prj.addMember(elt);

        // TODO: Does not work for packages.
        elt.setContainer(null);
      }
      clipboard.cutting = false;

    }
  }

  public boolean canPaste()
  {
    return clipboard.copiedElement != null;
  }

  public void updateActionStates()
  {
    Iterator it = actionMap.getWebActions();
    while (it.hasNext()) {
      WebAction action = (WebAction) it.next();
      updateActionState(action);
    }
  }

  public void updateActionState(WebAction action)
  {
    action.setEnabled(action.isEnabled(this));
    if (action.isSelectable()) {
      action.setSelected(action.isSelected(this));
    }
  }

  public IlrBrmRule getCurrentRuleTemplate()
  {
    return currentRuleTemplate;
  }

  public void updateCurrentRuleTemplate()
  {
    IlrProject project = this.currentProject;
    if (project != null) {
      IlrElementClass ruleClass
          = currentExtent.getElementClass(IlrBrmConstants.BRM_RULE_CLASS);
      IlrBrmRule ruleTemplate = null;
      Iterator it = project.getMembers().iterator();
      while (it.hasNext() && (ruleTemplate == null)) {
        Object o = it.next();
        if (o instanceof IlrLibrary) {
          IlrLibrary lib = (IlrLibrary) o;
          Iterator iter = lib.content();
          while (iter.hasNext() && (ruleTemplate == null)) {
            IlrModelElement elt = (IlrModelElement) iter.next();
            if (elt.getElementClass().isDerivedFrom(ruleClass)
                && ((IlrBrmRule) elt).isTemplate()) {
              ruleTemplate = (IlrBrmRule) elt;
            }
          }
        }
      }
      setCurrentRuleTemplate(ruleTemplate);
    }
  }

  public void setCurrentRuleTemplate(IlrBrmRule ruleTemplate)
  {
    this.currentRuleTemplate = ruleTemplate;
    if (ruleTemplate != null) {
      WebAction action = getWebAction(BuilderActions.ACTION_NEWRULE);
      action.setDisplayName(ruleTemplate.getName());
      IlrElementClass type = ruleTemplate.getElementClass();
      Iterator it = type.allAssignables().iterator();
      String icon = null;
      while (it.hasNext()) {
        IlrElementClass eltClass = (IlrElementClass) it.next();
        String name = eltClass.getQualifiedName().toString();
        String retVal
            = IlrWUtils.getIconResourceName("ui." + name + ".template.icon");
        if (retVal != null) {
          icon = retVal;
          break;
        }
      }
      if (icon != null) action.setIcon(icon);
    }
  }

  private void updateAddRuleMenu()
  {
    IlxWMenu menu = addRuleMenu;
    menu.removeAll();
    menu.invalidate();
    actionMap.removeWebActions(BuilderActions.ACTION_NEWRULE + ".");
    IlrProject project = getCurrentProject();
    int counter = 0;
    if (project != null) {
      Iterator it = project.getMembers().iterator();
      ArrayList libraries = new ArrayList();
      while (it.hasNext()) {
        Object o = it.next();
        if (o instanceof IlrLibrary) {
          IlrLibrary lib = (IlrLibrary) o;
          libraries.add(lib);
        }
      }
      int size = libraries.size();
      for (int i = 0; i < size; i++) {
        IlrLibrary lib = (IlrLibrary) libraries.get(i);
        Iterator iter = lib.content();
        IlxWMenu subMenu = null;
        if (size > 1) {
          subMenu = new IlxWMenu(lib.getName());
          menu.add(subMenu);
        }
        while (iter.hasNext()) {
          IlrModelElement elt = (IlrModelElement) iter.next();
          IlrElementClass ruleClass
              = getCurrentExtent().getElementClass(IlrBrmConstants.BRM_RULE_CLASS);
          if (elt.isInstanceOf(ruleClass, true)) {
            WebAction action
                = new BuilderActions
                .NewRuleFromModelAction(BuilderActions.ACTION_NEWRULE
                                        + "." + counter,
                                        (IlrBrmRule) elt);
            counter++;
            actionMap.registerWebAction(action);
            IlxWMenuItem mItem = action.makeMenuItem(this);
            // Once the item has been created and listeners have been
            // registered on it, update the action state so that the item
            // state is consistent with it.
            updateActionState(action);
            if (size > 1 && subMenu != null) {
              subMenu.add(mItem);
            } else {
              menu.add(mItem);
            }
          }
        }
      }
    }
  }

  private void updateOpenProjectMenu()
  {
    IlxWMenu menu = this.openProjectMenu;
    menu.removeAll();
    menu.invalidate();
    actionMap.removeWebActions(BuilderActions.ACTION_OPENPROJECT + ".");
    IlrRefPackage refPack = getCurrentExtent();
    if (refPack != null) {
      Iterator it = refPack.getRepository().content();
      int counter = 0;
      while (it.hasNext()) {
        Object obj = it.next();
        if (obj instanceof IlrProject) {
          IlrProject project = (IlrProject) obj;
          WebAction action
              = new BuilderActions
              .OpenProjectAction(BuilderActions.ACTION_OPENPROJECT
                                 + "." + counter,
                                 project);
          counter++;
          actionMap.registerWebAction(action);
          IlxWMenuItem item = action.makeMenuItem(this);
          // Once the item has been created and listeners have been
          // registered on it, update the action state so that the item
          // state is consistent with it.
          updateActionState(action);
          menu.add(item);
          // Add an element listener that will update the menu if the
          // project name changes.
          // First try to remove the listener in case it has already
          // been added.
          project.removeElementListener(openProjectMenuUpdater);
          project.addElementListener(openProjectMenuUpdater);
        }
      }
    }
    IlxWPort port = IlxWPort.getCurrentPort();
    if (port != null) {
      port.addUpdatingRequest(IlxWRequestDesc.getDesc("/jsp/header.jsp",
                                                      "header"));
    }
  }

  public void addMessage(String msg)
  {
    getMessagePanel().getMessageList().addMessage(msg);
  }

  public void addAlert(String msg)
  {
    getMessagePanel().getMessageList().addAlert(msg);
  }
  
  public ClientProperties getClientProperties() {
    if (clientProperties == null) {
      clientProperties = new ClientProperties();
      getManager().add(clientProperties);
    }
    return clientProperties;
  }

  public void setSkin(IlxWPort port, String resourceName)
  {
    IlxWManager mgr = getManager();
    this.skin = resourceName;
    if (resourceName == null || "".equals(resourceName)) {
      mgr.setAuthorRules(null);
    } else {
    	InputStream stream = null;	
      try {
        ServletContext application = port.getContext();
        stream = application.getResourceAsStream(resourceName);
        Reader reader = new InputStreamReader(stream);
        IlxWCSSRuleset ruleset = new IlxWCSSRuleset(reader);
        mgr.setAuthorRules(ruleset);
        reader.close();
      } catch (IOException e) {
        e.printStackTrace();
        return;
      } finally {
    	  if (stream != null) {
    		  IOUtils.closeQuietly(stream);
    	  }
      }
    }
    port.invalidatePage();
    updateActionStates();
  }

  private String skin;

  public String getCurrentSkin()
  {
    return skin;
  }

  protected static Logger getBuilderLogger()
  {
    Logger parent = LogManager.getLogManager().getLogger("ilog.rules");
    Logger logger
        = Logger.getLogger("gov.vha.edb.rules.web.builder",
                           "ilog.rules.util.prefs.IlrLoggerMessages");
    logger.setParent(parent);
    logger.setLevel(Level.ALL);
    return logger;
  }

  public Logger getLogger()
  {
    if (logger == null) {
      logger = getBuilderLogger();
    }
    return logger;
  }

}
