/* UtilLib_Servlet - Copyright (c) 2007-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 net.mapeadores.util.servlets.handlers;

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


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

    private final String text;
    private final String contentType;
    private long lastModified = ResponseHandler.LASTMODIFIED_NOCACHE;
    private String charset = "UTF-8";

    public SimpleResponseHandler(String text) {
        this.text = text;
        this.contentType = MimeTypeConstants.PLAIN;
    }

    public SimpleResponseHandler(String text, String contentType) {
        this.text = text;
        this.contentType = contentType;
    }

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

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

    public SimpleResponseHandler charset(String charset) {
        this.charset = charset;
        return this;
    }

    @Override
    public void handleResponse(HttpServletResponse response) throws IOException {
        response.setContentType(contentType + ";charset=" + charset);
        try (PrintWriter pw = response.getWriter()) {
            pw.print(text);
        }
    }

    public static SimpleResponseHandler init(String text) {
        return new SimpleResponseHandler(text);
    }

    public static SimpleResponseHandler init(String text, String contentType) {
        return new SimpleResponseHandler(text);
    }

}
