/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package org.jboss.media.util;

import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * DOM utils.
 *
 * @version <tt>$Revision: 1.1 $</tt>
 * @author <a href="mailto:ricardoarguello@users.sourceforge.net">Ricardo Argüello</a>
 */
public class DOMUtils
{
   public static Node findNode(Node node, String name)
   {
      if (node.getNodeName().equals(name))
      {
         return node;
      }
      if (node.hasChildNodes())
      {
         NodeList list = node.getChildNodes();
         int size = list.getLength();
         for (int i = 0; i < size; i++)
         {
            Node found = findNode(list.item(i), name);
            if (found != null)
               return found;
         }
      }
      return null;
   }

   public static String getNodeAttribute(Node node, String name)
   {
      if (node instanceof Element)
      {
         Element element = (Element) node;
         return element.getAttribute(name);
      }
      return null;
   }

   public void displayNode(Node root)
   {
      displayNode(root, 0);
   }

   public static void displayNode(Node node, int level)
   {
      indent(level);
      // emit open tag
      System.out.print("<" + node.getNodeName());
      NamedNodeMap map = node.getAttributes();
      if (map != null)
      {
         // print attribute values
         int length = map.getLength();
         for (int i = 0; i < length; i++)
         {
            Node attr = map.item(i);
            System.out.print(
               " " + attr.getNodeName() + "=\"" + attr.getNodeValue() + "\"");
         }
      }
      Node child = node.getFirstChild();
      if (child != null)
      {
         System.out.println(">"); // close current tag
         while (child != null)
         {
            // emit child tags recursively
            displayNode(child, level + 1);
            child = child.getNextSibling();
         }
         indent(level);
         // emit close tag
         System.out.println("</" + node.getNodeName() + ">");
      }
      else
      {
         System.out.println("/>");
      }
   }

   private static void indent(int level)
   {
      for (int i = 0; i < level; i++)
      {
         System.out.print("  ");
      }
   }
}
