/* BdfServer_HtmlProducers - Copyright (c) 2012-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.htmlproducers.mailing;

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.api.instruction.BdfInstructionConstants;
import fr.exemole.bdfserver.api.instruction.OutputParameters;
import fr.exemole.bdfserver.api.interaction.domains.MailingDomain;
import fr.exemole.bdfserver.commands.mailing.SendCommand;
import fr.exemole.bdfserver.email.EmailBuffer;
import fr.exemole.bdfserver.email.SendReport;
import fr.exemole.bdfserver.html.BdfServerHtmlProducer;
import fr.exemole.bdfserver.tools.instruction.OutputRequestHandler;
import net.mapeadores.util.logging.ErrorMessageException;


/**
 *
 * @author Vincent Calame
 */
public final class MailingHtmlProducerFactory {

    private MailingHtmlProducerFactory() {
    }

    public static BdfServerHtmlProducer getHtmlProducer(OutputParameters parameters) throws ErrorMessageException {
        OutputRequestHandler requestHandler = OutputRequestHandler.init(parameters);
        String page = parameters.getOutput();
        BdfServer bdfServer = parameters.getBdfServer();
        switch (page) {
            case MailingDomain.SEND_FORM_PAGE: {
                SendCommand.testSmtpManager(bdfServer);
                EmailBuffer emailBuffer = getEmailBuffer(requestHandler);
                return new SendFormHtmlProducer(parameters, emailBuffer);
            }
            case MailingDomain.SEND_REPORT_PAGE: {
                SendCommand.testSmtpManager(bdfServer);
                EmailBuffer emailBuffer = getEmailBuffer(requestHandler);
                SendReport sendReport = (SendReport) parameters.getResultObject(BdfInstructionConstants.SENDREPORT_OBJ);
                return new SendReportHtmlProducer(parameters, emailBuffer, sendReport);
            }
            default:
                return null;
        }
    }

    private static EmailBuffer getEmailBuffer(OutputRequestHandler requestHandler) throws ErrorMessageException {
        EmailBuffer emailBuffer = (EmailBuffer) requestHandler.getResultObject(BdfInstructionConstants.EMAILBUFFER_OBJ);
        if (emailBuffer == null) {
            emailBuffer = SendCommand.buildFromRequest(requestHandler, true);
        }
        return emailBuffer;
    }

}
