# MWDOM DOMVisitor
# Copyright (c)2001, MoonWolf. All right reserved.
module MWDOM
  class DOMVisitor
    # NodeType
    ELEMENT_Node                = 1
    ATTRIBUTE_Node              = 2
    TEXT_Node                   = 3
    CDATA_SECTION_Node          = 4
    ENTITY_REFERENCE_Node       = 5
    ENTITY_Node                 = 6
    PROCESSING_INSTRUCTION_Node = 7
    COMMENT_Node                = 8
    DOCUMENT_Node               = 9
    DOCUMENT_TYPE_Node          = 10
    DOCUMENT_FRAGMENT_Node      = 11
    NOTATION_Node               = 12
    
    Methods = {
      ELEMENT_Node,                :visit_Element,
      ATTRIBUTE_Node,              :visit_Attr,
      TEXT_Node,                   :visit_Text,
      CDATA_SECTION_Node,          :visit_CDATASection,
      ENTITY_REFERENCE_Node,       :visit_EntityReference,
      ENTITY_Node,                 :visit_Entity,
      PROCESSING_INSTRUCTION_Node, :visit_ProcessingInstruction,
      COMMENT_Node,                :visit_Comment,
      DOCUMENT_Node,               :visit_Document,
      DOCUMENT_TYPE_Node,          :visit_DocumentType,
      DOCUMENT_FRAGMENT_Node,      :visit_DocumentFragment,
      NOTATION_Node,               :visit_Notation
    }
    
    def visit(node,*rest,&iter)
      if sym=Methods[node.nodeType]
        send(sym,node,*rest,&iter)
      end
    end
    
    def visit_childNodes(node,*rest,&iter)
      retval = []
      c = node.childNodes
      idx = 0
      len = c.length
      while idx<len
        n=c.item(idx)
        retval.push visit(n,*rest,&iter)
        idx += 1
      end
      retval
    end
    
    def visit_Document(node,*rest,&iter)
      iter.call node,*rest if block_given?
      visit_childNodes(node,*rest,&iter)
    end
    
    def visit_DocumentType(node,*rest,&iter)
      iter.call node,*rest if block_given?
      visit_childNodes(node,*rest,&iter)
    end
    
    def visit_Element(node,*rest,&iter)
      iter.call node,*rest if block_given?
      visit_childNodes(node,*rest,&iter)
    end
    
    def visit_Text(node,*rest,&iter)
      iter.call node,*rest if block_given?
    end
    
    def visit_EntityReference(node,*rest,&iter)
      iter.call node,*rest if block_given?
    end
    
    def visit_Comment(node,*rest,&iter)
      iter.call node,*rest if block_given?
    end
    
    def visit_ProcessingInstruction(node,*rest,&iter)
      iter.call node,*rest if block_given?
    end
    
    def visit_CDATASection(node,*rest,&iter)
      iter.call node,*rest if block_given?
    end
    
    def visit_DocumentFragment(node,*rest,&iter)
      iter.call node,*rest if block_given?
      visit_childNodes(node,*rest,&iter)
    end
    
    def visit_Entity(node,*rest,&iter)
      iter.call node,*rest if block_given?
    end
    
    def visit_Notation(node,*rest,&iter)
      iter.call node,*rest if block_given?
    end
    
    def visit_Attr(node,*rest,&iter)
      iter.call node,*rest if block_given?
    end
  end
end
