/* BdfServer_Commands - 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.commands.corpus;

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.api.BdfServerConstants;
import fr.exemole.bdfserver.api.BdfServerEditor;
import fr.exemole.bdfserver.api.EditSession;
import fr.exemole.bdfserver.api.interaction.Domains;
import fr.exemole.bdfserver.api.ui.FieldUi;
import fr.exemole.bdfserver.api.ui.SpecialIncludeUi;
import fr.exemole.bdfserver.api.ui.SubsetIncludeUi;
import fr.exemole.bdfserver.api.ui.UiComponent;
import fr.exemole.bdfserver.api.ui.UiComponents;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import fr.exemole.bdfserver.tools.ui.components.FieldUiBuilder;
import fr.exemole.bdfserver.tools.ui.components.IncludeUiBuilder;
import fr.exemole.bdfserver.tools.ui.components.UiComponentBuilder;
import java.util.ArrayList;
import java.util.List;
import net.fichotheque.FichothequeConstants;
import net.fichotheque.corpus.Corpus;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;


/**
 *
 * @author Vincent Calame
 */
public class UiComponentOptionsCommand extends AbstractBdfCommand {

    public final static String COMMANDNAME = "UiComponentOptions";
    public final static String COMMANDKEY = "_ CRP-19";
    public final static String WIDTH_PARAMSUFFIX = "|width";
    public final static String ROWS_PARAMSUFFIX = "|rows";
    public final static String INPUT_PARAMSUFFIX = "|input";
    public final static String DEFAULT_PARAMSUFFIX = "|default";
    public final static String STATUS_PARAMSUFFIX = "|status";
    public final static String VARIANT_PARAMSUFFIX = "|variant";
    private Corpus corpus;
    private UiComponents uiComponents;
    private List<UiComponent> uiComponentList;

    public UiComponentOptionsCommand(BdfServer bdfServer, RequestMap requestMap) {
        super(bdfServer, requestMap);
    }

    @Override
    public boolean needSynchronisation() {
        return true;
    }

    @Override
    protected void doCommand() {
        boolean done = false;
        try (EditSession session = startEditSession(Domains.CORPUS, COMMANDNAME)) {
            BdfServerEditor bdfServerEditor = session.getBdfServerEditor();
            for (UiComponent componentUi : uiComponentList) {
                boolean stepDone = bdfServerEditor.putComponentUi(uiComponents, componentUi);
                if (stepDone) {
                    done = true;
                }
            }
        }
        putResultObject(CORPUS_OBJ, corpus);
        if (done) {
            setDone("_ done.corpus.uicomponentoptions");
        }
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        corpus = requestHandler.getMandatoryCorpus();
        checkSubsetAdmin(corpus);
        uiComponents = bdfServer.getUiManager().getMainUiComponents(corpus);
        uiComponentList = new ArrayList<UiComponent>();
        for (UiComponent uiComponent : uiComponents.getUiComponentList()) {
            if (uiComponent instanceof FieldUi) {
                FieldUi fieldUi = (FieldUi) uiComponent;
                String racine = fieldUi.getFieldString();
                FieldUiBuilder fieldUiBuilder = FieldUiBuilder.derive(fieldUi);
                update(racine, fieldUiBuilder);
                uiComponentList.add(fieldUiBuilder.toFieldUi());
            } else if (uiComponent instanceof SpecialIncludeUi) {
                SpecialIncludeUi includeUi = (SpecialIncludeUi) uiComponent;
                if ((includeUi.getName().equals(FichothequeConstants.LIAGE_NAME))) {
                    uiComponentList.add(IncludeUiBuilder.init(includeUi)
                            .setStatus(getStatus(includeUi.getName()))
                            .toIncludeUi());
                }
            } else if (uiComponent instanceof SubsetIncludeUi) {
                SubsetIncludeUi includeUi = (SubsetIncludeUi) uiComponent;
                IncludeUiBuilder includeUiBuilder = IncludeUiBuilder.init(includeUi);
                update(includeUi.getName(), includeUiBuilder);
                uiComponentList.add(includeUiBuilder.toIncludeUi());
            }
        }
    }

    private void update(String key, UiComponentBuilder uiComponentBuilder) throws ErrorMessageException {
        boolean ignoreSizeInput = false;
        uiComponentBuilder.setStatus(getStatus(key));
        if (requestHandler.hasParameter(key + VARIANT_PARAMSUFFIX)) {
            uiComponentBuilder.putOption(BdfServerConstants.INCLUDEVARIANT_OPTION, requestHandler.getMandatoryParameter(key + VARIANT_PARAMSUFFIX));
        }
        if (requestHandler.hasParameter(key + DEFAULT_PARAMSUFFIX)) {
            uiComponentBuilder.putOption(BdfServerConstants.DEFAULTVALUE_OPTION, requestHandler.getMandatoryParameter(key + DEFAULT_PARAMSUFFIX));
        }
        if (requestHandler.hasParameter(key + INPUT_PARAMSUFFIX)) {
            String inputType = requestHandler.getMandatoryParameter(key + INPUT_PARAMSUFFIX);
            if (inputType.equals(BdfServerConstants.INPUT_TEXT)) {
                inputType = "";
            }
            ignoreSizeInput = isIgnoreSizeInput(inputType);
            uiComponentBuilder.putOption(BdfServerConstants.INPUTTYPE_OPTION, inputType);
        }
        if (requestHandler.hasParameter(key + WIDTH_PARAMSUFFIX)) {
            String inputWidth = requestHandler.getMandatoryParameter(key + WIDTH_PARAMSUFFIX);
            if (ignoreSizeInput) {
                inputWidth = "";
            }
            try {
                uiComponentBuilder.putOption(BdfServerConstants.INPUTWIDTH_OPTION, inputWidth);
            } catch (IllegalArgumentException iae) {
                throw BdfErrors.unknownParameterValue(key + WIDTH_PARAMSUFFIX, inputWidth);
            }
        }
        String rows = getRows(key);
        if (rows != null) {
            if (ignoreSizeInput) {
                rows = "";
            }
            uiComponentBuilder.putOption(BdfServerConstants.INPUTROWS_OPTION, rows);
        }
    }

    private String getStatus(String key) throws ErrorMessageException {
        String status = requestHandler.getTrimedParameter(key + STATUS_PARAMSUFFIX);
        if (!status.isEmpty()) {
            try {
                return BdfServerConstants.checkValidStatus(status);
            } catch (IllegalArgumentException iae) {
                throw BdfErrors.unknownParameterValue(key + STATUS_PARAMSUFFIX, status);
            }
        } else {
            return null;
        }
    }

    private String getRows(String key) throws ErrorMessageException {
        String rows = requestHandler.getTrimedParameter(key + ROWS_PARAMSUFFIX);
        try {
            int r = Integer.parseInt(rows);
            if (r > 0) {
                return String.valueOf(r);
            }
        } catch (NumberFormatException nfe) {
        }
        return null;
    }

    private static boolean isIgnoreSizeInput(String type) {
        switch (type) {
            case "":
            case BdfServerConstants.INPUT_TEXT:
                return false;
            default:
                return true;
        }

    }

}
