/* 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.InputStream;
import java.io.OutputStream;
import java.time.Instant;
import javax.servlet.http.HttpServletResponse;
import net.mapeadores.util.io.DocStream;
import net.mapeadores.util.io.IOUtils;
import net.mapeadores.util.servlets.ResponseHandler;


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

    private final DocStream docStream;
    private String fileName = null;

    public DocStreamResponseHandler(DocStream docStream) {
        this.docStream = docStream;
    }

    public DocStreamResponseHandler(DocStream docStream, String fileName) {
        this.docStream = docStream;
        this.fileName = fileName;
    }

    @Override
    public Instant getLastModified() {
        long l = docStream.getLastModified();
        if (l == -1) {
            return ResponseHandler.LASTMODIFIED_NOCACHE;
        }
        return Instant.ofEpochMilli(l);
    }

    public DocStreamResponseHandler fileName(String fileName) {
        this.fileName = fileName;
        return this;
    }

    @Override
    public void handleResponse(HttpServletResponse response) throws IOException {
        String contentType = docStream.getMimeType();
        String charset = docStream.getCharset();
        if (charset != null) {
            contentType = contentType + ";charset=" + charset;
        }
        response.setContentType(contentType);
        int length = docStream.getLength();
        if (length > -1) {
            response.setContentLength(length);
        }
        if (fileName != null) {
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        }
        try (InputStream is = docStream.getInputStream(); OutputStream os = response.getOutputStream()) {
            IOUtils.copy(is, os);
        }
    }

    public static DocStreamResponseHandler init(DocStream docStream) {
        return new DocStreamResponseHandler(docStream);
    }

}
