/* 
 * E-XML Library:  For XML, XML-RPC, HTTP, and related.
 * Copyright (C) 2002-2008  Elias Ross
 * 
 * genman@noderunner.net
 * http://noderunner.net/~genman
 * 
 * 1025 NE 73RD ST
 * SEATTLE WA 98115
 * USA
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * $Id$
 */

package net.noderunner.exml;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * This class is for holding a root element.
 * Processing instructions and comments not belonging to any element can be
 * added as well.
 * @see Element
 */
public class Document 
	implements Node
{
	private List<Node> children;

	/**
	 * Constructs a new document with no children.
	 */
	public Document() {
	}

	/**
	 * Returns the value <code>DOCUMENT_NODE</code>.
	 */
	public short getNodeType() {
		return DOCUMENT_NODE;
	}

	/**
	 * Returns the list of child nodes.
	 * @return returns null if no children in this object
	 */
	public List<Node> getChildNodes() {
		return children;
	}

	/**
	 * Returns the root element of this document.
	 * @return null if no root element was found
	 */
	public Element getRootElement() {
		if (children == null) 
			return null;
		Iterator<Node> i = children.iterator();
		while (i.hasNext()) {
			Node n = i.next();
			if (n.getNodeType() == ELEMENT_NODE)
				return (Element)n;
		}
		return null;
	}

	/**
	 * Appends a child node to this Document.
	 * @param n child node to append
	 * @throws ElementException if this node is an
	 * element, and a root element already exists.
	 */
	public void appendChild(Node n) 
	{
		if (n.getNodeType() == ELEMENT_NODE && getRootElement() != null)
			throw new ElementException("Attempt to add another root element");
		if (children == null) 
		{
			children = new ArrayList<Node>();
		}
		children.add(n);
	}

	/**
	 * Returns a string representation of this document, containing
	 * all this document's children.
	 * @return a string version of the Document
	 */
	public String toString() {
		StringBuffer sb = new StringBuffer(64);
		sb.append("<?xml version='1.0'?>\r\n");
		if (children != null) {
			Iterator<Node> i = children.iterator();
			while (i.hasNext()) {
				sb.append(i.next().toString());
			}
		}
		return sb.toString();
	}
}
