/* 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.misc;

import fr.exemole.bdfserver.api.exportation.table.FicheTableParameters;
import fr.exemole.bdfserver.api.exportation.table.TableExportParameters;
import fr.exemole.bdfserver.api.instruction.BdfParameters;
import fr.exemole.bdfserver.api.interaction.GetConstants;
import fr.exemole.bdfserver.api.interaction.InteractionConstants;
import fr.exemole.bdfserver.api.managers.TableExportManager;
import fr.exemole.bdfserver.api.users.BdfUserPrefs;
import fr.exemole.bdfserver.html.BdfHtmlUtils;
import fr.exemole.bdfserver.html.BdfServerHtmlProducer;
import fr.exemole.bdfserver.html.consumers.Button;
import fr.exemole.bdfserver.html.consumers.Grid;
import fr.exemole.bdfserver.html.consumers.PageUnit;
import fr.exemole.bdfserver.html.consumers.SelectOption;
import fr.exemole.bdfserver.html.consumers.attributes.Deploy;
import fr.exemole.bdfserver.html.forms.TableExportFormHtml;
import fr.exemole.bdfserver.html.jslib.BdfJsLibs;
import fr.exemole.bdfserver.tools.exportation.table.FicheTableParametersBuilder;
import fr.exemole.bdfserver.tools.exportation.table.TableExportParametersBuilder;
import java.util.List;
import java.util.Map;
import net.fichotheque.exportation.table.TableExportConstants;
import net.fichotheque.exportation.table.TableExportDescription;
import net.fichotheque.selection.SelectionDef;
import net.mapeadores.util.html.HA;
import net.mapeadores.util.text.StringUtils;


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

    private final static SelectOption EMPTY_OPTION = SelectOption.init("").text("---");
    private final TableExportManager tableExportManager;

    public TableExportFormHtmlProducer(BdfParameters bdfParameters) {
        super(bdfParameters);
        this.tableExportManager = bdfServer.getTableExportManager();
        addJsLib(BdfJsLibs.DEPLOY);
        addThemeCss("misc.css");
    }

    @Override
    public void printHtml() {
        Map<String, String> storeMap = getStoredValues("form_tableexport");
        TableExportParameters tableExportParameters = initTableExportParameters(bdfUser.getPrefs(), storeMap);
        start();
        this
                .__(PageUnit.start("action-Ods", "_ title.tableexport.stream"))
                .FORM_get(HA.action(GetConstants.TABLES_ROOT + "/" + GetConstants.GET_MULTI).attr("data-formstorage-key", "tableExportForm"))
                .__(printTableExportChoice(tableExportParameters, storeMap))
                .__(TableExportFormHtml.HEADERTYPE_TITLE)
                .__(TableExportFormHtml.printHeaderTypeRadios(this, tableExportParameters.getHeaderType()))
                .__(printSelectionFilter(storeMap))
                .__(printSpreadMerge(storeMap))
                .__(Button.COMMAND, Button.submit("action-Ods", "_ submit.tableexport.stream_ods"))
                ._FORM()
                .__(PageUnit.END);
        end();
    }

    private boolean printTableExportChoice(TableExportParameters tableExportParameters, Map<String, String> storeMap) {
        String defaultDivId = generateId();
        String nameDivId = generateId();
        List<TableExportDescription> tableExportDescriptionList = tableExportManager.getValidTableExportDescriptionList();
        if (!tableExportDescriptionList.isEmpty()) {
            String tableExportName = tableExportParameters.getTableExportName();
            boolean isDefault = (tableExportName == null);
            this
                    .__(Grid.START)
                    .__(Grid.radioRow("_ label.tableexport.tableexport_name", name(GetConstants.DEFAULTEXPORT_PARAMNAME).value("0").checked(!isDefault).populate(Deploy.radio(nameDivId)),
                            () -> {
                                this
                                        .DIV(Grid.detailPanelTable().id(nameDivId).addClass(isDefault, "hidden"))
                                        .__(Grid.selectRow("_ label.global.tableexport", name(InteractionConstants.TABLEEXPORT_PARAMNAME),
                                                () -> {
                                                    for (TableExportDescription current : tableExportDescriptionList) {
                                                        String currentName = current.getName();
                                                        boolean selected = false;
                                                        if ((tableExportName != null) && (currentName.equals(tableExportName))) {
                                                            selected = true;
                                                        }
                                                        String title = current.getTitle(workingLang);
                                                        if (title.equals(currentName)) {
                                                            title = "";
                                                        } else {
                                                            title = " " + title;
                                                        }
                                                        this
                                                                .OPTION(currentName, selected)
                                                                .__escape("[")
                                                                .__escape(currentName)
                                                                .__escape("]")
                                                                .__escape(title)
                                                                ._OPTION();
                                                    }
                                                }))
                                        .__(Grid.checkboxRow("_ label.tableexport.withthesaurustable", name(GetConstants.THESAURUSTABLE_PARAMNAME).value("1").checked(storeMap)))
                                        ._DIV();
                            }))
                    .__(Grid.radioRow("_ label.tableexport.tableexport_default", name(GetConstants.DEFAULTEXPORT_PARAMNAME).value("1").checked(isDefault).populate(Deploy.radio(defaultDivId)),
                            () -> {
                                this
                                        .DIV(HA.id(defaultDivId).classes("global-DetailPanel").addClass(!isDefault, "hidden"))
                                        .__(TableExportFormHtml.printWithParameters(this, tableExportParameters.getDefaulFicheTableParameters()))
                                        .__(TableExportFormHtml.printPatternModeRadios(this, tableExportParameters.getDefaulFicheTableParameters().getPatternMode()))
                                        ._DIV();
                            }))
                    .__(Grid.END);
        } else {
            this
                    .__(TableExportFormHtml.printWithParameters(this, tableExportParameters.getDefaulFicheTableParameters()))
                    .__(TableExportFormHtml.printPatternModeRadios(this, tableExportParameters.getDefaulFicheTableParameters().getPatternMode()));
        }
        return true;
    }

    private boolean printSpreadMerge(Map<String, String> storeMap) {
        this
                .__(Grid.START)
                .__(Grid.checkboxRow("_ label.tableexport.spreadsheetmerge", name(GetConstants.MERGE_PARAMNAME).value("1").checked(storeMap)))
                .__(Grid.END);
        return true;
    }

    private boolean printSelectionFilter(Map<String, String> storeMap) {
        List<SelectionDef> selectionDefList = bdfServer.getSelectionManager().getSelectionDefList();
        if (selectionDefList.isEmpty()) {
            return false;
        }
        List<SelectOption> optionList = BdfHtmlUtils.toAvailableOptionList(selectionDefList, workingLang);
        if (optionList.isEmpty()) {
            return false;
        }
        optionList.add(0, EMPTY_OPTION);
        String current = storeMap.get(InteractionConstants.SELECTION_PARAMNAME);
        if (current == null) {
            current = "";
        }
        this
                .__(Grid.START)
                .__(Grid.selectRow("_ label.tableexport.selectionfilter", name(InteractionConstants.SELECTION_PARAMNAME), SelectOption.consumer(optionList, current)))
                .__(Grid.END);
        return true;
    }

    private TableExportParameters initTableExportParameters(BdfUserPrefs prefs, Map<String, String> storeMap) {
        Parser parser = new Parser(prefs, storeMap);
        return parser.init();
    }


    private static class Parser {

        private final BdfUserPrefs prefs;
        private final TableExportParametersBuilder builder;
        private final Map<String, String> storeMap;

        private Parser(BdfUserPrefs prefs, Map<String, String> storeMap) {
            this.prefs = prefs;
            this.storeMap = storeMap;
            this.builder = new TableExportParametersBuilder();
        }

        private TableExportParameters init() {
            return TableExportParametersBuilder.init()
                    .setTableExportName(initTableExportName())
                    .setFicheTableParameters(initFicheTableParameters())
                    .setHeaderType(initHeaderType())
                    .toTableExportParameters();
        }

        private String initTableExportName() {
            String defaultExport = storeMap.get(GetConstants.DEFAULTEXPORT_PARAMNAME);
            if ((defaultExport != null) && (defaultExport.equals("0"))) {
                return storeMap.get(InteractionConstants.TABLEEXPORT_PARAMNAME);
            }
            return null;
        }

        private String initHeaderType() {
            String headerType = storeMap.get(InteractionConstants.HEADERTYPE_PARAMNAME);
            if (headerType == null) {
                return prefs.getDefaultHeaderType();
            }
            try {
                return TableExportConstants.checkHeaderType(headerType);
            } catch (IllegalArgumentException iae) {
                return prefs.getDefaultHeaderType();
            }
        }

        private FicheTableParameters initFicheTableParameters() {
            String patternMode = storeMap.get(InteractionConstants.PATTERNMODE_PARAMNAME);
            if (patternMode == null) {
                return prefs.getDefaultFicheTableParameters();
            }
            FicheTableParametersBuilder ficheTableParametersBuilder = new FicheTableParametersBuilder();
            try {
                ficheTableParametersBuilder.setPatternMode(patternMode);
            } catch (IllegalArgumentException iae) {
            }
            String withString = storeMap.get(InteractionConstants.WITH_PARAMNAME);
            if (withString != null) {
                String[] tokens = StringUtils.getTokens(withString, ';', StringUtils.EMPTY_EXCLUDE);
                for (String token : tokens) {
                    ficheTableParametersBuilder.putWith(token);
                }
            }
            return ficheTableParametersBuilder.toFicheTableParameters();
        }


    }

}
