/* BdfServer_Email - Copyright (c) 2011-2024 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 fr.exemole.bdfserver.email.datasource;

import fr.exemole.bdfserver.tools.exportation.transformation.TransformerParameters;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.Map;
import javax.activation.DataSource;
import net.fichotheque.exportation.transformation.StreamTemplate;
import net.mapeadores.util.exceptions.ShouldNotOccurException;


/**
 *
 * @author Vincent Calame
 */
class XsltStreamDataSource implements DataSource {

    private final static Map<String, String> EMPTY_OUTPUTPROPERTIES = Collections.emptyMap();
    private final String name;
    private final String extractionString;
    private final StreamTemplate.Xslt streamTemplate;
    private final TransformerParameters transformerParameters;

    XsltStreamDataSource(String name, StreamTemplate.Xslt streamTemplate, String extractionString, TransformerParameters transformerParameters) {
        this.name = name;
        this.streamTemplate = streamTemplate;
        this.extractionString = extractionString;
        this.transformerParameters = transformerParameters;
    }

    @Override
    public String getContentType() {
        return streamTemplate.getMimeType();
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        ByteArrayOutputStream byteoutput = new ByteArrayOutputStream();
        try {
            streamTemplate.transform(extractionString, byteoutput, transformerParameters.getMap(), EMPTY_OUTPUTPROPERTIES);
        } catch (IOException ioe) {
            throw new ShouldNotOccurException(ioe);
        }
        return new ByteArrayInputStream(byteoutput.toByteArray());
    }

    @Override
    public OutputStream getOutputStream() throws IOException {
        throw new IOException("no editable source");
    }


}
