package org.apache.slide.projector.value;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.i18n.LocalizedError;
import org.apache.slide.projector.repository.RepositoryException;
import org.jdom.DocType;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class ElementValue  extends AbstractStreamable implements XMLValue {
    private final static XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());

    private Element element;
    private byte[] bytes = null;

    public ElementValue(Element element) {
        this.element = element;
    }

    public InputStream getInputStream() throws RepositoryException {
        if ( bytes == null ) {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            try {
                xmlOutputter.output(element, outputStream);
            } catch ( IOException exception ) {
                throw new RepositoryException(new LocalizedError("IOException"), exception);
            }
            bytes = outputStream.toByteArray();
        }
        InputStream inputStream = new ByteArrayInputStream(bytes);
        return inputStream;
    }

    public void enableMultipleStreaming() {}

    public int getContentLength() {
        return 1;
    }

    public boolean isDocument() {
        return false;
    }

    public DocType getDocumentType() {
        return new DocType(element.getName());
    }

    public Element getRootElement() {
        return element;
    }

    public String getCharacterEncoding() {
        return "UTF-8";
    }
}
