/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 */
package groovy.xml

/**
 * A Groovy builder that emits XML using a StAX writer.
 * <p>
 * Typical usage:
 * <pre class="groovyTestCase">
 * import javax.xml.stream.XMLOutputFactory
 * def factory = XMLOutputFactory.newInstance()
 * def writer = new StringWriter()
 * def builder = new groovy.xml.StaxBuilder(factory.createXMLStreamWriter(writer))
 * builder.root1(a:5, b:7) {
 *     elem1('hello1')
 *     elem2('hello2')
 *     elem3(x:7)
 * }
 * def pretty = writer.toString()
 *     .replaceAll(/<\?xml[^>]*>/, '') // remove XML declaration
 * assert pretty in ['<root1 a="5" b="7"><elem1>hello1</elem1><elem2>hello2</elem2><elem3 x="7"></elem3></root1>',
 *                   '<root1 a="5" b="7"><elem1>hello1</elem1><elem2>hello2</elem2><elem3 x="7"/></root1>']
 * </pre>
 * StAX-compatible writers from external libraries, such as Jettison, may also be used.
 */
class StaxBuilder extends BuilderSupport {

    /** Writer receiving the XML document generated by this builder. */
    def writer

    /**
     * Creates a builder that writes a new XML document to the supplied StAX writer.
     *
     * @param xmlStreamWriter writer that receives generated XML events
     */
    StaxBuilder(xmlStreamWriter) {
        writer = xmlStreamWriter
        writer.writeStartDocument()
    }

    /**
     * Creates an element with no attributes or body text.
     *
     * @param name element name
     * @return the node token used by {@link BuilderSupport}
     */
    protected createNode(name) {
        createNode(name, null, null)
    }

    /**
     * Creates an element containing simple text content.
     *
     * @param name element name
     * @param value text value to write inside the element
     * @return the node token used by {@link BuilderSupport}
     */
    protected createNode(name, value) {
        createNode(name, null, value)
    }

    /**
     * Creates an element with attributes and no body text.
     *
     * @param name element name
     * @param attributes attribute values to write on the element
     * @return the node token used by {@link BuilderSupport}
     */
    protected createNode(name, Map attributes) {
        createNode(name, attributes, null)
    }

    /**
     * Creates an element and writes any supplied attributes and text content.
     *
     * @param name element name
     * @param attributes attribute values to write on the element
     * @param value text value to write inside the element
     * @return the node token used by {@link BuilderSupport}
     */
    protected createNode(name, Map attributes, value) {
        writer.writeStartElement(name.toString())
        if (attributes) {
            attributes.each { k, v ->
                writer.writeAttribute(k.toString(), v.toString())
            }
        }
        if (value) {
            writer.writeCharacters(value.toString())
        }
        name
    }

    /**
     * Closes the current element and finalizes the document when the root node completes.
     *
     * @param parent parent node token, or {@code null} for the document root
     * @param node completed node token
     */
    @SuppressWarnings('UnusedMethodParameter')
    protected void nodeCompleted(parent, node) {
        writer.writeEndElement()
        if (!parent) {
            writer.writeEndDocument()
            writer.flush()
        }
    }

    /**
     * No-op for StAX output because parent relationships are managed by the stream writer itself.
     *
     * @param parent parent node token
     * @param child child node token
     */
    @SuppressWarnings(['UnusedMethodParameter', 'EmptyMethod'])
    protected void setParent(parent, child) {
    }

}
