package org.plenix.jsp.parser;

import org.w3c.dom.*;
import java.io.*;
import com.ibm.xml.parser.*;
import java.util.*;

import org.plenix.jsp.ResourceManager;

class TagDefinition
{
  private static Hashtable tags = null;
  public static final String DEFAULT_VERSION = "0.92";

  private static String version;

  static
  {
    setVersion(DEFAULT_VERSION);
  }

  protected static void setVersion(String name)
  {
    version = "tags-" + name + ".xml";
  }

  protected static TagDefinition get(String string)
  {
    if (tags == null)
    {
      try
      {
        tags = new Hashtable();
        InputStream input = ResourceManager.getResourceStream(version);

        TXDocument tXDocument = new com.ibm.xml.parser.Parser(version).readStream(input);
        traverse(tXDocument.getDocumentElement(), tags);
      }
      catch (Exception IOException)
      {
        System.err.println("TagDefinition: Unable to load tag resource file '" + version + "'");
	return null;
      }
    }

    return (TagDefinition)tags.get(string);
  }

  private static void traverse(Node node, Hashtable table)
  {
    if (node.getNodeType() == Node.ELEMENT_NODE)
    {
      Element element = (Element)node;
      String nodeName = element.getTagName();

      if (nodeName.equalsIgnoreCase("tag"))
      {
        String tagName = element.getAttribute("name").toLowerCase();
        String tagEmpty = element.getAttribute("empty").toLowerCase();
        String tagBody = element.getAttribute("body").toLowerCase();

        TagDefinition definition = new TagDefinition(tagName, tagEmpty.equals("true"), tagBody.equals("true"));

        table.put(tagName, definition);

        return;
      }

      NodeList nodeList = node.getChildNodes();
      int childCount = nodeList.getLength();

      for (int i = 0; i < childCount; i++)
        traverse(nodeList.item(i), table);
    }
  }

  private String name;
  private boolean empty;
  private boolean body;

  protected TagDefinition(String theName, boolean isEmpty, boolean isBody)
  {
    name = theName;
    empty = isEmpty;
    body = isBody;
  }

  protected String getName()
  {
    return name;
  }

  protected boolean inBody()
  {
    return body;
  }

  protected boolean isEmpty()
  {
    return empty;
  }
}
