package org.dbxml.xml.dom.traversal;

/*
 * dbXML License, Version 1.0
 *
 *
 * Copyright (c) 1999-2001 The dbXML Group, L.L.C.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by
 *        The dbXML Group (http://www.dbxml.com/)."
 *    Alternately, this acknowledgment may appear in the software
 *    itself, if and wherever such third-party acknowledgments normally
 *    appear.
 *
 * 4. The names "dbXML" and "The dbXML Group" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    info@dbxml.com.
 *
 * 5. Products derived from this software may not be called "dbXML",
 *    nor may "dbXML" appear in their name, without prior written
 *    permission of The dbXML Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE DBXML GROUP OR ITS CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id: TreeWalkerImpl.java,v 1.5 2001/05/23 00:36:25 tom Exp $
 */

import org.dbxml.xml.dom.*;
import org.w3c.dom.*;
import org.w3c.dom.traversal.*;
import java.util.*;

/**
 * TreeWalkerImpl
 */

public final class TreeWalkerImpl implements TreeWalker, NodeIterator {
   protected boolean valid = true;
   protected Node root = null;
   protected Node next = null;
   protected int whatToShow = NodeFilter.SHOW_ALL;
   protected NodeFilter filter = null;
   protected boolean expand = false;

   public TreeWalkerImpl(Node root, int whatToShow, NodeFilter filter, boolean entityReferenceExpansion) throws DOMException {
      this.root = null;
      next = root;
      this.whatToShow = whatToShow;
      this.filter = filter;
      this.expand = entityReferenceExpansion;
      if ( acceptNode(root) )
         next = root;
      else
         nextNode();
   }

   public int getShowType(Node node) {
      switch ( node.getNodeType() ) {
         case Node.ATTRIBUTE_NODE:              return NodeFilter.SHOW_ATTRIBUTE;
         case Node.CDATA_SECTION_NODE:          return NodeFilter.SHOW_CDATA_SECTION;
         case Node.COMMENT_NODE:                return NodeFilter.SHOW_COMMENT;
         case Node.DOCUMENT_FRAGMENT_NODE:      return NodeFilter.SHOW_DOCUMENT_FRAGMENT;
         case Node.DOCUMENT_NODE:               return NodeFilter.SHOW_DOCUMENT;
         case Node.DOCUMENT_TYPE_NODE:          return NodeFilter.SHOW_DOCUMENT_TYPE;
         case Node.ELEMENT_NODE:                return NodeFilter.SHOW_ELEMENT;
         case Node.ENTITY_NODE:                 return NodeFilter.SHOW_ENTITY;
         case Node.ENTITY_REFERENCE_NODE:       return NodeFilter.SHOW_ENTITY_REFERENCE;
         case Node.NOTATION_NODE:               return NodeFilter.SHOW_NOTATION;
         case Node.PROCESSING_INSTRUCTION_NODE: return NodeFilter.SHOW_PROCESSING_INSTRUCTION;
         case Node.TEXT_NODE:                   return NodeFilter.SHOW_TEXT;
         default:                               return 0;
      }
   }

   public boolean acceptNode(Node node) {
      return ( (getShowType(node) & whatToShow) > 0 )
            && (filter == null
            || (filter != null
            && filter.acceptNode(node) == NodeFilter.FILTER_ACCEPT) );
   }

   /**
    *  The root node of the Iterator, as specified when it was created.
    */
   public Node getRoot() {
      return root;
   }

   /**
    *  This attribute determines which node types are presented via the
    * iterator. The available set of constants is defined in the
    * <code>NodeFilter</code> interface.
    */
   public int getWhatToShow() {
      return whatToShow;
   }

   /**
    *  The filter used to screen nodes.
    */
   public NodeFilter getFilter() {
      return filter;
   }

   /**
    *  The value of this flag determines whether the children of entity
    * reference nodes are visible to the iterator. If false, they will be
    * skipped over.
    * <br> To produce a view of the document that has entity references
    * expanded and does not expose the entity reference node itself, use the
    * whatToShow flags to hide the entity reference node and set
    * expandEntityReferences to true when creating the iterator. To produce
    * a view of the document that has entity reference nodes but no entity
    * expansion, use the whatToShow flags to show the entity reference node
    * and set expandEntityReferences to false.
    */
   public boolean getExpandEntityReferences() {
      return expand;
   }

   /**
    *  Detaches the iterator from the set which it iterated over, releasing
    * any computational resources and placing the iterator in the INVALID
    * state. After<code>detach</code> has been invoked, calls to
    * <code>nextNode</code> or<code>previousNode</code> will raise the
    * exception INVALID_STATE_ERR.
    */
   public void detach() {
      valid = false;
   }

   /**
    *  The node at which the TreeWalker is currently positioned.
    * <br> The value must not be null. Alterations to the DOM tree may cause
    * the current node to no longer be accepted by the TreeWalker's
    * associated filter. currentNode may also be explicitly set to any node,
    * whether or not it is within the subtree specified by the root node or
    * would be accepted by the filter and whatToShow flags. Further
    * traversal occurs relative to currentNode even if it is not part of the
    * current view by applying the filters in the requested direction (not
    * changing currentNode where no traversal is possible).
    * @exception DOMException
    *    NOT_SUPPORTED_ERR: Raised if the specified <code>currentNode</code>
    *   is<code>null</code> .
    */
   public Node getCurrentNode() {
      return next;
   }

   public void setCurrentNode(Node currentNode) throws DOMException {
      if ( !valid )
         throw NodeImpl.EX_INVALID_STATE;
      next = currentNode;
   }

   /**
    *  Moves to and returns the closest visible ancestor node of the current
    * node. If the search for parentNode attempts to step upward from the
    * TreeWalker's root node, or if it fails to find a visible ancestor
    * node, this method retains the current position and returns null.
    * @return  The new parent node, or null if the current node has no parent
    *   in the TreeWalker's logical view.
    */
   public Node parentNode() {
      Node node = next;
      while ( node != null ) {
         if ( node == root )
            return null;
         node = node.getParentNode();
         if ( node == null )
            return null;
         else if ( acceptNode(node) ) {
            next = node;
            return next;
         }
      }
      return null;
   }

   /**
    *  Moves the <code>TreeWalker</code> to the first visible child of the
    * current node, and returns the new node. If the current node has no
    * visible children, returns <code>null</code> , and retains the current
    * node.
    * @return  The new node, or <code>null</code> if the current node has no
    *   visible children in the TreeWalker's logical view.
    */
   public Node firstChild() {
      Node node = next.getFirstChild();
      while ( node != null ) {
         if ( acceptNode(node) ) {
            next = node;
            return next;
         }
         else
            node = node.getNextSibling();
      }
      return null;
   }

   /**
    *  Moves the <code>TreeWalker</code> to the last visible child of the
    * current node, and returns the new node. If the current node has no
    * visible children, returns <code>null</code> , and retains the current
    * node.
    * @return  The new node, or <code>null</code> if the current node has no
    *   children  in the TreeWalker's logical view.
    */
   public Node lastChild() {
      Node node = next.getLastChild();
      while ( node != null ) {
         if ( acceptNode(node) ) {
            next = node;
            return next;
         }
         else
            node = node.getPreviousSibling();
      }
      return null;
   }

   /**
    *  Moves the <code>TreeWalker</code> to the previous sibling of the
    * current node, and returns the new node. If the current node has no
    * visible previous sibling, returns <code>null</code> , and retains the
    * current node.
    * @return  The new node, or <code>null</code> if the current node has no
    *   previous sibling in the TreeWalker's logical view.
    */
   public Node previousSibling() {
      Node node = next.getPreviousSibling();
      while ( node != null ) {
         if ( acceptNode(node) ) {
            next = node;
            return next;
         }
         else
            node = node.getPreviousSibling();
      }
      return null;
   }

   /**
    *  Moves the <code>TreeWalker</code> to the next sibling of the current
    * node, and returns the new node. If the current node has no visible
    * next sibling, returns <code>null</code> , and retains the current node.
    * @return  The new node, or <code>null</code> if the current node has no
    *   next sibling in the TreeWalker's logical view.
    */
   public Node nextSibling() {
      Node node = next.getNextSibling();
      while ( node != null ) {
         if ( acceptNode(node) ) {
            next = node;
            return next;
         }
         else
            node = node.getNextSibling();
      }
      return null;
   }

   /**
    *  Moves the <code>TreeWalker</code> to the previous visible node in
    * document order relative to the current node, and returns the new node.
    * If the current node has no previous node,  or if the search for
    * previousNode attempts to step upward from the TreeWalker's root node,
    * returns <code>null</code> , and retains the current node.
    * @return  The new node, or <code>null</code> if the current node has no
    *   previous node in the TreeWalker's logical view.
    */
   public Node previousNode() {
      Node node = next;
      while ( true ) {
         node = node.getPreviousSibling();
         if ( node == null )
            node = node.getParentNode();
         else
            while ( node.hasChildNodes() )
               node = node.getLastChild();
         if ( node != null && acceptNode(node) ) {
            next = node;
            return next;
         }
         else if ( node == null )
            return null;
      }
   }

   /**
    * Moves the <code>TreeWalker</code> to the next visible node in document
    * order relative to the current node, and returns the new node. If the
    * current node has no next node,  or if the search for nextNode attempts
    * to step upward from the TreeWalker's root node, returns
    * <code>null</code> , and retains the current node.
    * @return  The new node, or <code>null</code> if the current node has no
    *   next node  in the TreeWalker's logical view.
    */
   public Node nextNode() {
      Node result = null;
      if ( next != null )
         result = next;
      else
         return null;
      Node node = next;
      while ( true ) {
         if ( node.hasChildNodes() )
            node = node.getFirstChild();
         else {
            while ( true ) {
               Node old = node;
               node = node.getNextSibling();
               if ( node == null ) {
                  node = old;
                  /*
                  if ( node == root ) {
                     next = null;
                     return result;
                  }
                   */
                  node = node.getParentNode();
                  if ( node == null || node == root ) {
                     next = null;
                     return result;
                  }
               }
               else
                  break;
            }
         }
         if ( node != null && acceptNode(node) ) {
            next = node;
            return result;
         }
      }
   }
}
