/* BdfServer_Get - Copyright (c) 2011-2025 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.get.streamproducers;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import net.fichotheque.album.Illustration;
import net.fichotheque.album.metadata.AlbumDim;
import net.mapeadores.util.io.IOUtils;
import net.mapeadores.util.io.StreamProducer;
import net.mapeadores.util.servlets.exceptions.InternalErrorException;


/**
 *
 * @author Vincent Calame
 */
public class IllustrationStreamProducer implements StreamProducer {

    private final String fileName;
    private final Illustration illustration;
    private final AlbumDim albumDim;
    private final String specialDim;

    public IllustrationStreamProducer(String fileName, Illustration illustration, AlbumDim albumDim) {
        this.fileName = fileName;
        this.illustration = illustration;
        this.albumDim = albumDim;
        this.specialDim = null;
    }

    public IllustrationStreamProducer(String fileName, Illustration illustration, String specialDim) {
        this.fileName = fileName;
        this.illustration = illustration;
        this.albumDim = null;
        this.specialDim = specialDim;
    }

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

    @Override
    public String getCharset() {
        return null;
    }

    @Override
    public String getFileName() {
        return fileName;
    }

    @Override
    public void writeStream(OutputStream outputStream) throws IOException {
        InputStream inputStream;
        if (albumDim != null) {
            inputStream = illustration.getInputStream(albumDim);
        } else {
            inputStream = illustration.getInputStream(specialDim);
        }
        if (inputStream == null) {
            throw new InternalErrorException("_ error.exception.internalerror", "input stream is null (" + illustration.getFileName() + ")");
        }
        try (InputStream is = inputStream) {
            IOUtils.copy(is, outputStream);
        }
    }

}
