/*$cb
 *    This file is a part of libopenmhp.
 *
 *    Copyright (C) 2005 Mikko Novaro <miknov@gmail.com>
 *
 *    See main header file (libopenmhp/openmhp.h) for licensing and
 *    contact information.
 $ce*/

package libopenmhp.xmlhandler;

import java.util.List;
import java.util.ArrayList;
import org.xml.sax.Attributes;

/** Base class of classes corresponding to different
 * XML-elements. Nodes form a tree structure
 * representing the xml -document being parsed.
 * By overwriting methods (such as) start and end,
 * successor classes can perform actions requested
 * by the xml-document. */
public abstract class XMLElement {

    /** Child nodes of current node.
     * Elements of the list are of type XMLElement. */
    private List childNodes;

    private XMLElement parentNode;

    /** Contains PCDATA from the element. */
    private String pcData;

    /** Contains attributes of the element. Must be set with
     * setAttributes -method. In case there are no attributes,
     * the variable shall contain an empty Attributes object. */
    private Attributes attributes;

    public XMLElement() {
        childNodes = new ArrayList();
        pcData = "";
    }

    public void setAttributes(Attributes attrib) {
        assert attrib != null;
        attributes = attrib;
    }

    /** Called when corresponding xml-element begins. */
    public void start() {}

    /** Called when corresponding xml-element ends. */
    public void end() {}

    /** Called when corresponding xml-element contains character data. */
    public void characters(String data) {
        pcData = pcData + data;
    }

    /** Adds a child node for the current node. */
    public void addChildNode(XMLElement child) {
        childNodes.add(child);
    }

    public void setParentNode(XMLElement parent) {
        parentNode = parent;
    }

    public XMLElement getParentNode() {
        return parentNode;
    }

    /** Returns the number of node's child nodes. */
    public int countChildNodes() { return childNodes.size(); }

    /** Returns a child node with the given index. */
    public XMLElement getChildNode(int i) {
        return (XMLElement)childNodes.get(i);
    }

    /** Finds the first child node that if of a class of a
     * given name. Search is case insensitive. */
    public XMLElement getChildNode(String className)
        throws ElementNotFoundException
    {
        className = "libopenmhp.xmlhandler.elem."+className.toLowerCase();
        for (int i = 0; i < childNodes.size(); i++) {
            Object o = childNodes.get(i);
            if (className.equals(o.getClass().getName().toLowerCase()))
                return (XMLElement)o;
        }
        throw new ElementNotFoundException("Child element \"" +
            className + "\" was not found.");
    }

    public String getData() {return pcData;}
}
