/* UtilLib_Servlet - Copyright (c) 2010-2020 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.servlets.handlers;

import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.http.HttpServletResponse;
import net.mapeadores.util.io.StreamProducer;
import net.mapeadores.util.mimetype.MimeTypeConstants;
import net.mapeadores.util.servlets.ResponseHandler;


/**
 *
 * @author Vincent Calame
 */
public class StreamResponseHandler implements ResponseHandler {

    private final StreamProducer streamProducer;
    private long lastModified = ResponseHandler.LASTMODIFIED_NOCACHE;
    private String mimeType = MimeTypeConstants.OCTETSTREAM;
    private String charset = null;
    private String fileName = null;
    private int length = -1;

    public StreamResponseHandler(StreamProducer streamProducer) {
        this.streamProducer = streamProducer;
        String producerMimeType = streamProducer.getMimeType();
        if (producerMimeType != null) {
            this.mimeType = producerMimeType;
        }
        this.charset = streamProducer.getCharset();
        this.fileName = streamProducer.getFileName();
    }

    @Override
    public long getLastModified() {
        return lastModified;
    }

    public StreamResponseHandler lastModified(long lastModified) {
        this.lastModified = lastModified;
        return this;
    }

    @Override
    public void handleResponse(HttpServletResponse response) throws IOException {
        String contentType = mimeType;
        if (charset != null) {
            contentType = contentType + ";charset=" + charset;
        }
        response.setContentType(contentType);
        if (length > -1) {
            response.setContentLength(length);
        }
        if (fileName != null) {
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        }
        try (OutputStream output = response.getOutputStream()) {
            streamProducer.writeStream(output);
        }
    }

    public static StreamResponseHandler init(StreamProducer streamProducer) {
        return new StreamResponseHandler(streamProducer);
    }

}
