/* BdfServer_HtmlProducers - Copyright (c) 2013-2024 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.main;

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.api.interaction.Domains;
import fr.exemole.bdfserver.api.interaction.GetConstants;
import fr.exemole.bdfserver.api.interaction.InteractionConstants;
import fr.exemole.bdfserver.api.interaction.domains.MailingDomain;
import fr.exemole.bdfserver.api.interaction.domains.MainDomain;
import fr.exemole.bdfserver.api.namespaces.BdfUserSpace;
import fr.exemole.bdfserver.api.users.BdfUser;
import fr.exemole.bdfserver.html.BdfHtmlConstants;
import fr.exemole.bdfserver.html.BdfServerHtmlProducer;
import fr.exemole.bdfserver.html.consumers.Button;
import fr.exemole.bdfserver.html.consumers.Tree;
import fr.exemole.bdfserver.tools.BH;
import fr.exemole.bdfserver.tools.BdfHref;
import fr.exemole.bdfserver.tools.BdfHrefProvider;
import fr.exemole.bdfserver.tools.exportation.table.BdfTableExportUtils;
import fr.exemole.bdfserver.tools.instruction.BdfInstructionUtils;
import fr.exemole.bdfserver.tools.instruction.RequestHandler;
import java.util.List;
import net.fichotheque.Subset;
import net.fichotheque.SubsetKey;
import net.fichotheque.corpus.Corpus;
import net.fichotheque.corpus.FicheMeta;
import net.fichotheque.corpus.Fiches;
import net.fichotheque.exportation.table.TableExportDescription;
import net.fichotheque.thesaurus.Thesaurus;
import net.fichotheque.utils.CorpusUtils;
import net.mapeadores.util.html.HtmlAttributes;
import net.mapeadores.util.html.HtmlPrinter;
import net.mapeadores.util.html.HtmlWrapper;
import net.mapeadores.util.localisation.Lang;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;


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

    public final static HtmlWrapper DISPLAYTABLE_TREE = Tree.tree("displaytable-Tree");
    public final static HtmlWrapper DISPLAYTABLE_LEAF = Tree.leaf("displaytable-Leaf");
    public final static BdfHrefProvider DEFAULT_BDFHREFPROVIDER = new DefaultBdfHrefProvider();

    private MainHtmlUtils() {
    }

    public static BdfHrefProvider getMainProvider(RequestMap requestMap) {
        String fiche = requestMap.getParameter("fiche");
        if (fiche != null) {
            return new FicheBdfHrefProvider(fiche);
        }
        return DEFAULT_BDFHREFPROVIDER;
    }

    public static Fiches getFiches(RequestHandler requestHandler) throws ErrorMessageException {
        if (requestHandler.hasParameter(SubsetKey.CATEGORY_CORPUS_STRING)) {
            FicheMeta ficheMeta = requestHandler.getMandatoryFicheMeta();
            return CorpusUtils.toSingletonFiches(ficheMeta);
        }
        return requestHandler.getBdfUser().getSelectedFiches();
    }

    public static String getMainPageName(BdfServerHtmlProducer bhp) {
        if (bhp.isWithJavascript()) {
            return BdfInstructionUtils.getAbsolutePageName(Domains.MAIN, MainDomain.IFRAMES_PAGE);
        } else {
            return BdfInstructionUtils.getAbsolutePageName(Domains.MAIN, MainDomain.FRAMESET_PAGE);
        }
    }

    public static boolean printTableDisplayDetails(BdfServerHtmlProducer hp, BdfServer bdfServer, BdfUser bdfUser, Subset subset, boolean withFicheMailing, HtmlAttributes detailsAttributes) {
        SubsetKey subsetKey = subset.getSubsetKey();
        List<TableExportDescription> list = BdfTableExportUtils.getAvailableTableExportDescriptionList(bdfServer.getTableExportManager(), subset.getSubsetKey(), "table");
        String currentTableExportName = bdfUser.getPrefs().getAttributes().getFirstValue(BdfUserSpace.toTableAttributeKey(subset));
        TableExportDescription currentTableExportDescription = null;
        if (currentTableExportName != null) {
            for (TableExportDescription tableExportDescription : list) {
                String name = tableExportDescription.getName();
                if (name.equals(currentTableExportName)) {
                    currentTableExportDescription = tableExportDescription;
                    break;
                }
            }
            if (currentTableExportDescription == null) {
                currentTableExportName = null;
            }
        }
        String titleKey = "_ link.main.tabledisplay";
        if (subset instanceof Corpus) {
            titleKey = "_ link.main.tabledisplay_fiches";
        } else if (subset instanceof Thesaurus) {
            titleKey = "_ link.main.tabledisplay_motcles";
        }
        Lang workingLang = bdfUser.getWorkingLang();
        hp
                .DETAILS(detailsAttributes)
                .SUMMARY()
                .__localize(titleKey)
                ._SUMMARY()
                .__(DISPLAYTABLE_TREE, () -> {
                    for (TableExportDescription tableExportDescription : list) {
                        String name = tableExportDescription.getName();
                        hp
                                .__(DISPLAYTABLE_LEAF, () -> {
                                    hp
                                            .SPAN("displaytable-Title")
                                            .__escape(tableExportDescription.getTitle(workingLang))
                                            .__colon()
                                            ._SPAN()
                                            .__(printSupplementaryLinks(hp, subsetKey, name, withFicheMailing));
                                });
                    }
                    hp
                            .__(DISPLAYTABLE_LEAF, () -> {
                                hp
                                        .SPAN("displaytable-Title displaytable-Default")
                                        .__localize("_ link.main.defaulttableformat")
                                        .__colon()
                                        ._SPAN()
                                        .__(printSupplementaryLinks(hp, subsetKey, null, withFicheMailing));
                            });
                })
                ._DETAILS();

        return true;
    }

    private static boolean printSupplementaryLinks(HtmlPrinter hp, SubsetKey subsetKey, String tableExportName, boolean withMailing) {
        BdfHref displayHref = BH.domain(Domains.MAIN).page(MainDomain.TABLEDISPLAY_PAGE).param(InteractionConstants.SUBSET_PARAMNAME, subsetKey.getKeyString()).param(MainDomain.REMEMBER_ACTION_PARAMNAME, "1");
        String subsetKeyString = subsetKey.getKeyString();
        String urlPrefix = GetConstants.TABLES_ROOT + "/" + subsetKeyString;
        if (tableExportName != null) {
            urlPrefix = urlPrefix + "-" + tableExportName;
            displayHref.param(InteractionConstants.TABLEEXPORT_PARAMNAME, tableExportName);
        }
        Button button = Button.link().style(Button.TRANSPARENT_STYLE);
        hp
                .__(button.href(displayHref).action("action-TableDisplay").tooltipMessage("_ link.global.version", "HTML").target(BdfHtmlConstants.EDITION_FRAME))
                .__(button.href(urlPrefix + ".csv").action("action-Csv").tooltipMessage("_ link.global.version", "CSV").target(null))
                .__(button.href(urlPrefix + ".ods").action("action-Ods").tooltipMessage("_ link.global.version", "ODS").target(null));
        if (withMailing) {
            BdfHref sendHref = BH.domain(Domains.MAILING).page(MailingDomain.SEND_FORM_PAGE).subset(subsetKey).param("type", MailingDomain.TABLEEXPORT_SENDTYPE);
            if (tableExportName != null) {
                sendHref.tableExport(tableExportName);
            }
            hp
                    .__(button.href(sendHref).action("action-Send").tooltipMessage("_ link.global.send").target(BdfHtmlConstants.EDITION_FRAME));
        }
        return true;
    }


    private static class DefaultBdfHrefProvider extends BdfHrefProvider {

        private DefaultBdfHrefProvider() {

        }

        @Override
        public BdfHref getSrc(String name) {
            switch (name) {
                case BdfHtmlConstants.LIST_FRAME:
                    return BH.domain(Domains.MAIN).page(MainDomain.FICHES_PAGE);
                case BdfHtmlConstants.EDITION_FRAME:
                    return BH.domain(Domains.MAIN).page(MainDomain.START_PAGE);
                default:
                    return null;
            }
        }

    }


    private static class FicheBdfHrefProvider extends BdfHrefProvider {

        private final String fiche;

        private FicheBdfHrefProvider(String fiche) {
            this.fiche = fiche;
        }

        @Override
        public BdfHref getSrc(String name) {
            switch (name) {
                case BdfHtmlConstants.LIST_FRAME: {
                    BdfHref bdfHref = BH.domain(Domains.MAIN).page(MainDomain.FICHES_PAGE);
                    String[] tokens = fiche.split("-");
                    if (tokens.length > 1) {
                        bdfHref.param("corpus", tokens[0]);
                        bdfHref.param("id", tokens[1]);
                    }
                    return bdfHref;
                }
                case BdfHtmlConstants.EDITION_FRAME: {
                    BdfHref bdfHref = new BdfHref("fiches/" + fiche + ".html", true);
                    return bdfHref;
                }
                default:
                    return null;
            }
        }

    }

}
