/* BdfServer_HtmlProducers - Copyright (c) 2011-2023 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.instruction.BdfParameters;
import fr.exemole.bdfserver.api.interaction.domains.MailingDomain;
import fr.exemole.bdfserver.email.EmailBuffer;
import fr.exemole.bdfserver.email.SendReport;
import fr.exemole.bdfserver.email.TableExportEmail;
import fr.exemole.bdfserver.email.ValidAddress;
import fr.exemole.bdfserver.html.BdfServerHtmlProducer;
import fr.exemole.bdfserver.html.consumers.JunctionSelection;
import fr.exemole.bdfserver.html.consumers.PageUnit;
import fr.exemole.bdfserver.html.consumers.SubsetIcon;
import fr.exemole.bdfserver.html.consumers.Tree;
import java.util.List;
import java.util.Set;
import net.fichotheque.corpus.Corpus;
import net.fichotheque.corpus.FicheMeta;
import net.fichotheque.corpus.Fiches;
import net.fichotheque.tools.corpus.FichesBuilder;
import net.fichotheque.utils.CorpusMetadataUtils;
import net.fichotheque.utils.CorpusUtils;
import net.fichotheque.utils.FichothequeUtils;
import net.mapeadores.util.exceptions.SwitchException;


/**
 *
 * @author Vincent Calame
 */
public class SendReportHtmlProducer extends BdfServerHtmlProducer {

    private final EmailBuffer emailBuffer;
    private final SendReport sendReport;

    public SendReportHtmlProducer(BdfParameters bdfParameters, EmailBuffer emailBuffer, SendReport sendReport) {
        super(bdfParameters);
        this.emailBuffer = emailBuffer;
        this.sendReport = sendReport;
        addThemeCss("mailing.css");
    }

    @Override
    public void printHtml() {
        start();
        this
                .__(PageUnit.start("action-Send", "_ title.mailing.sendreport"))
                .__(printCommandMessage())
                .__(printAttachmentList())
                .__(printFicheList())
                .__(printAddressList(EmailBuffer.TO_FIELD, "_ title.mailing.sendreport_to"))
                .__(printAddressList(EmailBuffer.CC_FIELD, "_ title.mailing.sendreport_cc"))
                .__(printAddressList(EmailBuffer.BCC_FIELD, "_ title.mailing.sendreport_bcc"))
                .__(PageUnit.END);
        end();
    }

    private boolean printAttachmentList() {
        if (sendReport == null) {
            return false;
        }
        List<String> attachmentList = sendReport.getAttachmentList();
        if (attachmentList.isEmpty()) {
            return false;
        }
        this
                .H2()
                .__localize("_ title.mailing.sendreport_attachments")
                ._H2()
                .__(Tree.TREE, () -> {
                    for (String fileName : attachmentList) {
                        this
                                .__(Tree.LEAF, () -> {
                                    this
                                            .__escape(fileName);
                                });
                    }
                });
        return true;
    }

    private boolean printFicheList() {
        String sendType = emailBuffer.getSendType();
        this
                .H2()
                .__localize(getTitleKey(sendType))
                ._H2()
                .__(printFiches(getFiches()));
        return true;
    }

    private boolean printFiches(Fiches fiches) {
        if (fiches.isEmpty()) {
            this
                    .P()
                    .__localize("_ info.mailing.fiches_none")
                    ._P();
            return true;
        }
        this
                .UL("global-JunctionList");
        for (Fiches.Entry entry : fiches.getEntryList()) {
            Corpus corpus = entry.getCorpus();
            this
                    .LI()
                    .P()
                    .__(SubsetIcon.CORPUS)
                    .__escape(FichothequeUtils.getTitle(corpus, workingLang))
                    ._P()
                    .__(JunctionSelection.TREE, () -> {
                        for (FicheMeta ficheMeta : entry.getFicheMetaList()) {

                            this
                                    .__(Tree.LEAF, () -> {
                                        this
                                                .SPAN("mailing-Fiche")
                                                .__escape(CorpusMetadataUtils.getFicheTitle(ficheMeta, workingLang, formatLocale))
                                                ._SPAN();
                                    });
                        }
                    })
                    ._LI();
        }
        this
                ._UL();
        return true;
    }

    private boolean printAddressList(String fieldName, String l10nKey) {
        boolean selfBcc = ((fieldName.equals(EmailBuffer.BCC_FIELD)) && (emailBuffer.isWithRedacteurBcc()));
        List<ValidAddress> list = emailBuffer.getValidAddressList(fieldName);
        if ((list.isEmpty()) && (!selfBcc)) {
            return false;
        }
        this
                .H2()
                .__localize(l10nKey)
                ._H2()
                .__(Tree.TREE, () -> {
                    for (ValidAddress validAddress : list) {
                        this
                                .__(Tree.LEAF, () -> {
                                    this
                                            .__escape(validAddress.getEmailCore().toCompleteString(true));
                                });
                    }
                    if (selfBcc) {
                        this
                                .__(Tree.LEAF, () -> {
                                    this
                                            .__escape(emailBuffer.getRedacteurEmail().toCompleteString(true));
                                });
                    }

                });
        return true;
    }

    private Fiches getFiches() {
        Object sendObject = emailBuffer.getSendObject();
        switch (emailBuffer.getSendType()) {
            case MailingDomain.FICHE_SENDTYPE:
                return CorpusUtils.toSingletonFiches((FicheMeta) sendObject);
            case MailingDomain.COMPILATION_SENDTYPE:
                return bdfUser.getSelectedFiches();
            case MailingDomain.SELECTION_SENDTYPE:
                return FichesBuilder.init().addAll((Set<FicheMeta>) sendObject).toFiches();
            case MailingDomain.TABLEEXPORT_SENDTYPE:
                return CorpusUtils.reduce(bdfUser.getSelectedFiches(), ((TableExportEmail) sendObject).getCorpus());
            default:
                throw new SwitchException("Unknown sendType: " + emailBuffer.getSendType());
        }
    }

    private static String getTitleKey(String sendType) {
        switch (sendType) {
            case MailingDomain.FICHE_SENDTYPE:
                return "_ title.mailing.sendreport_fiches";
            case MailingDomain.COMPILATION_SENDTYPE:
                return "_ title.mailing.sendreport_compilation";
            case MailingDomain.SELECTION_SENDTYPE:
                return "_ title.mailing.sendreport_fiches";
            case MailingDomain.TABLEEXPORT_SENDTYPE:
                return "_ title.mailing.sendreport_tableexport";
            default:
                throw new SwitchException("Unknown sendType: " + sendType);
        }
    }

}
