/* UtilLib_Servlet - Copyright (c) 2010-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 java.time.Instant;
import javax.servlet.http.HttpServletResponse;
import net.mapeadores.util.mimetype.MimeTypeConstants;
import net.mapeadores.util.servlets.ResponseHandler;
import net.mapeadores.util.xml.XmlProducer;


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

    private final XmlProducer xmlProducer;
    private final String contentType;
    private Instant lastModified = ResponseHandler.LASTMODIFIED_NOCACHE;

    public XmlResponseHandler(XmlProducer xmlProducer) {
        this.xmlProducer = xmlProducer;
        this.contentType = MimeTypeConstants.XML;
    }

    public XmlResponseHandler(XmlProducer xmlProducer, String contentType) {
        this.xmlProducer = xmlProducer;
        this.contentType = contentType;
    }

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

    public XmlResponseHandler lastModified(Instant lastModified) {
        this.lastModified = lastModified;
        return this;
    }

    @Override
    public void handleResponse(HttpServletResponse response) throws IOException {
        response.setContentType(contentType + ";charset=UTF-8");
        try (PrintWriter pw = response.getWriter()) {
            xmlProducer.writeXml(pw);
        }
    }

    public static XmlResponseHandler init(XmlProducer xmlProducer) {
        return new XmlResponseHandler(xmlProducer);
    }

    public static XmlResponseHandler init(XmlProducer xmlProducer, String contentType) {
        return new XmlResponseHandler(xmlProducer, contentType);
    }

}
