package com.srbenoit.xml;

import java.util.ArrayList;
import java.util.List;

/**
 * An element, characterized by a pair of tags of the form &lt; ... &gt; and &lt;/ ... &gt;.
 */
public class NonemptyElement extends ElementBase implements Node {

    /** version number for serialization */
    private static final long serialVersionUID = -7401017410745873815L;

    /** the opening tag span of the element */
    public final transient TagSpan openTagSpan;

    /** the list of children of this element */
    public final transient List<Node> children;

    /**
     * Constructs a new <code>Element</code>.
     *
     * @param  tag   the parsed tag name
     * @param  span  the tag span for the open tag
     */
    public NonemptyElement(final String tag, final TagSpan span) {

        super(tag);

        this.openTagSpan = span;
        this.children = new ArrayList<Node>(4);
    }

    /**
     * Generates the print representation of the node (may recursively call this method on child
     * nodes).
     *
     * @param   xml  the source XML
     * @return  the print representation
     */
    public String print(final String xml) {

        StringBuilder str;
        String key;
        String value;

        str = new StringBuilder(200);

        str.append('<');
        str.append(this.tagName);

        for (String attr : keySet()) {
            key = encode(attr);
            value = encode(get(attr));

            str.append(' ');
            str.append(key);
            str.append('=');
            str.append(value.contains("'") ? "\"" : "'");
            str.append(value);
            str.append(value.contains("'") ? "\"" : "'");
        }

        str.append(">");

        // Append children
        for (Node child : this.children) {
            str.append(child.print(xml));
        }

        str.append("</");
        str.append(this.tagName);
        str.append(">");

        return str.toString();
    }
}
