/* UtilLib - Copyright (c) 2012-2019 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package net.mapeadores.util.xml;

import java.io.ByteArrayOutputStream;
import javax.xml.transform.sax.SAXSource;
import net.mapeadores.util.primitives.io.PrimitivesIOFactory;
import net.mapeadores.util.primitives.io.PrimitivesReader;
import net.mapeadores.util.primitives.io.PrimitivesWriter;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;


/**
 *
 * @author Vincent Calame
 */
public class XMLBuffer {

    private ByteArrayOutputStream byteArrayOutputStream;
    private byte[] byteArray;
    private InputSource inputSource = new InputSource();

    public XMLBuffer() {
        byteArrayOutputStream = new ByteArrayOutputStream();
    }

    public XMLWriter getXMLWriter() {
        if (byteArrayOutputStream == null) {
            throw new IllegalStateException("flush done before !");
        }
        PrimitivesWriter primitivesWriter = PrimitivesIOFactory.newWriter(byteArrayOutputStream);
        return new PrimitivesXMLWriter(primitivesWriter);
    }

    public void flush() {
        this.byteArray = byteArrayOutputStream.toByteArray();
        this.byteArrayOutputStream = null;
    }

    private XMLReader getXMLReader() {
        PrimitivesReader primitivesReader = PrimitivesIOFactory.newReader(byteArray);
        return new PrimitivesSAXReader(primitivesReader);
    }

    public SAXSource toSAXSource() {
        return new SAXSource(getXMLReader(), inputSource);
    }

}
