/* BdfServer_HtmlProducers - Copyright (c) 2011-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.selection;

import fr.exemole.bdfserver.api.instruction.BdfParameters;
import fr.exemole.bdfserver.api.interaction.Domains;
import fr.exemole.bdfserver.api.interaction.InteractionConstants;
import fr.exemole.bdfserver.api.interaction.domains.MainDomain;
import fr.exemole.bdfserver.api.interaction.domains.SelectionDomain;
import fr.exemole.bdfserver.api.users.BdfUserConstants;
import fr.exemole.bdfserver.commands.selection.UserDefaultSelectionCommand;
import fr.exemole.bdfserver.commands.selection.UserSelectionChangeCommand;
import fr.exemole.bdfserver.html.BdfHtmlConstants;
import fr.exemole.bdfserver.html.BdfHtmlUtils;
import fr.exemole.bdfserver.html.BdfServerHtmlProducer;
import fr.exemole.bdfserver.html.ParameterMap;
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.forms.SelectionFormPrinter;
import fr.exemole.bdfserver.html.jslib.MiscJsLibs;
import fr.exemole.bdfserver.tools.BH;
import fr.exemole.bdfserver.tools.users.BdfUserUtils;
import java.util.List;
import net.fichotheque.corpus.SortConstants;
import net.fichotheque.permission.PermissionSummary;
import net.fichotheque.selection.FicheQuery;
import net.fichotheque.selection.SelectionDef;
import net.mapeadores.util.html.HA;
import net.mapeadores.util.html.JsObject;
import net.mapeadores.util.request.RequestConstants;


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

    public final static String BEFORE_INSERT = "before";
    public final static String AFTER_INSERT = "after";
    private final static SelectOption[] SORTTYPE_OPTIONS = {
        SelectOption.init(SortConstants.TITLE_ASC).textL10nObject("_ label.selection.sorttype_title"),
        SelectOption.init(SortConstants.ID_ASC).textL10nObject("_ label.selection.sorttype_id"),
        SelectOption.init(SortConstants.CREATIONDATE_DESC).textL10nObject("_ label.selection.sorttype_creationdate"),
        SelectOption.init(SortConstants.MODIFICATIONDATE_DESC).textL10nObject("_ label.selection.sorttype_modificationdate")
    };
    private final PermissionSummary permissionSummary;
    private final String sortType;
    private FicheQuery ficheQuery;

    public SelectFormHtmlProducer(BdfParameters bdfParameters, String selectionName) {
        super(bdfParameters);
        this.permissionSummary = bdfParameters.getPermissionSummary();
        addJsLib(MiscJsLibs.SELECTFORM);
        addThemeCss("selectform.css");
        initFicheQuery(selectionName);
        initHook(SelectFormHtmlProducer.class);
        this.sortType = BdfUserUtils.getCurrentSortType(bdfServer, bdfUser);
    }

    private void initFicheQuery(String selectionName) {
        if (selectionName != null) {
            if (selectionName.equals("_default")) {
                ficheQuery = bdfUser.getPrefs().getDefaultFicheQuery();
            }
        }
        if (ficheQuery == null) {
            ficheQuery = bdfUser.getFicheQuery();
        }
    }

    @Override
    public void printHtml() {
        start();
        this
                .SCRIPT()
                .__jsObject("SelectForm.ARGS", initSelectFormArgs())
                ._SCRIPT();
        printToolBarLinks();
        insertInclude(BEFORE_INSERT);
        printStandardUnit();
        printSelectionDefUnit();
        insertInclude(AFTER_INSERT);
        end();
    }

    public FicheQuery getFicheQuery() {
        return ficheQuery;
    }

    protected void printToolBarLinks() {
        this
                .DIV("global-PageToolbar")
                .__(printPageLink("action-defaultselection-Save", "_ link.selection.default_save", RequestConstants.COMMAND_PARAMETER, UserDefaultSelectionCommand.COMMANDNAME))
                .__space()
                .__(printPageLink("action-defaultselection-Load", "_ link.selection.default_load", SelectionDomain.SELECTIONNAME_PARAMNAME, "_default"))
                ._DIV();
    }

    private void printStandardUnit() {
        this
                .__(PageUnit.start("action-Selection", "_ title.selection.fichesselection").sectionCss("unit-Unit selectform-Unit"))
                .FORM_get(Domains.SELECTION, BdfHtmlConstants.LIST_FRAME)
                .INPUT_hidden(ParameterMap.init()
                        .command(UserSelectionChangeCommand.COMMANDNAME)
                        .page(Domains.MAIN, MainDomain.FICHES_PAGE))
                .P("selectform-Submit")
                .__(printHtmlSelectSortType())
                .__space()
                .__(Button.submit("action-Selection", "_ submit.selection.selectionchange"))
                ._P()
                .__(SelectionFormPrinter.init(getFicheQuery(), bdfServer, bdfUser, permissionSummary, this)
                        .printFieldsets()
                )
                ._FORM()
                .__(PageUnit.END);
    }

    private boolean printSelectionDefUnit() {
        List<SelectionDef> selectionDefList = bdfServer.getSelectionManager().getSelectionDefList();
        if (selectionDefList.isEmpty()) {
            return false;
        }
        List<SelectOption> optionList = BdfHtmlUtils.toAvailableOptionList(selectionDefList, workingLang);
        if (optionList.isEmpty()) {
            return false;
        }
        String current = "";
        Object currentValue = bdfUser.getParameterValue(BdfUserConstants.SELECTION_DEFNAME);
        if ((currentValue != null) && (currentValue instanceof String)) {
            current = (String) currentValue;
        }
        this
                .__(PageUnit.start("action-Selection", "_ title.selection.byselectiondef"))
                .FORM_get(Domains.SELECTION, BdfHtmlConstants.LIST_FRAME)
                .INPUT_hidden(ParameterMap.init()
                        .command(UserSelectionChangeCommand.COMMANDNAME)
                        .page(Domains.MAIN, MainDomain.FICHES_PAGE)
                        .param(UserSelectionChangeCommand.SELECTIONTYPE_PARAMNAME, UserSelectionChangeCommand.SELECTIONDEF_TYPE_PARAMVALUE))
                .__(Grid.START)
                .__(Grid.selectRow("_ label.global.selectiondef", name(InteractionConstants.SELECTION_PARAMNAME), SelectOption.consumer(optionList, current)))
                .__(Grid.selectRow("_ label.selection.sorttype", name(UserSelectionChangeCommand.SORTTYPE_PARAMNAME), SelectOption.consumer(SORTTYPE_OPTIONS, sortType)))
                .__(Grid.END)
                .__(Button.COMMAND,
                        Button.submit("action-Selection", "_ submit.selection.selectionchange"))
                ._FORM()
                .__(PageUnit.END);
        return true;
    }

    private boolean printPageLink(String actionClass, String titleLocKey, String extraParamName, String extraParamValue) {
        this
                .A(HA.href(BH.domain(Domains.SELECTION).page(SelectionDomain.SELECTFORM_PAGE).param(extraParamName, extraParamValue)).classes("global-button-Transparent global-button-Transparent32").addClass(actionClass).titleLocKey(titleLocKey))
                .__(Button.ICON)
                ._A();
        return true;
    }

    protected boolean printHtmlSelectSortType() {
        this
                .SPAN()
                .__localize("_ label.selection.sorttype")
                .__colon()
                ._SPAN()
                .SELECT(UserSelectionChangeCommand.SORTTYPE_PARAMNAME)
                .__(SelectOption.consumer(SORTTYPE_OPTIONS, sortType))
                ._SELECT();
        return true;
    }

    private JsObject initSelectFormArgs() {
        String dateInputsType = bdfUser.getPrefs().getDateInputsType();
        return JsObject.init()
                .put("dateInputs", dateInputsType);
    }

}
