/* BdfServer - Copyright (c) 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.tools.instruction;

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.api.exportation.table.FicheTableParameters;
import fr.exemole.bdfserver.api.interaction.InteractionConstants;
import fr.exemole.bdfserver.api.managers.TableExportManager;
import fr.exemole.bdfserver.api.managers.TransformationManager;
import fr.exemole.bdfserver.api.roles.Role;
import fr.exemole.bdfserver.tools.exportation.table.FicheTableParametersBuilder;
import fr.exemole.bdfserver.tools.exportation.transformation.BdfTransformationUtils;
import java.text.ParseException;
import java.util.Comparator;
import net.fichotheque.Subset;
import net.fichotheque.SubsetItem;
import net.fichotheque.SubsetKey;
import net.fichotheque.addenda.Addenda;
import net.fichotheque.addenda.Document;
import net.fichotheque.album.Album;
import net.fichotheque.album.Illustration;
import net.fichotheque.album.metadata.AlbumDim;
import net.fichotheque.corpus.Corpus;
import net.fichotheque.corpus.FicheMeta;
import net.fichotheque.corpus.SortConstants;
import net.fichotheque.exportation.access.AccessDef;
import net.fichotheque.exportation.balayage.BalayageContentDescription;
import net.fichotheque.exportation.balayage.BalayageDescription;
import net.fichotheque.exportation.scrutari.ScrutariExportDef;
import net.fichotheque.exportation.sql.SqlExportDef;
import net.fichotheque.exportation.table.TableExportConstants;
import net.fichotheque.exportation.table.TableExportContentDescription;
import net.fichotheque.exportation.table.TableExportDescription;
import net.fichotheque.exportation.transformation.TemplateContentDescription;
import net.fichotheque.exportation.transformation.TemplateDescription;
import net.fichotheque.exportation.transformation.TemplateKey;
import net.fichotheque.exportation.transformation.TransformationDescription;
import net.fichotheque.exportation.transformation.TransformationKey;
import net.fichotheque.selection.FicheQuery;
import net.fichotheque.selection.FichothequeQueries;
import net.fichotheque.selection.MotcleQuery;
import net.fichotheque.selection.SelectionDef;
import net.fichotheque.sphere.Redacteur;
import net.fichotheque.sphere.Sphere;
import net.fichotheque.thesaurus.Motcle;
import net.fichotheque.thesaurus.Thesaurus;
import net.fichotheque.tools.selection.FichothequeQueriesBuilder;
import net.fichotheque.tools.selection.SelectionDOMUtils;
import net.fichotheque.utils.BalayageUtils;
import net.fichotheque.utils.Comparators;
import net.fichotheque.utils.TableExportUtils;
import net.fichotheque.utils.ThesaurusUtils;
import net.fichotheque.utils.selection.FicheSelectorBuilder;
import net.fichotheque.utils.selection.MotcleSelectorBuilder;
import net.mapeadores.util.io.ResourceUtils;
import net.mapeadores.util.localisation.Lang;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;
import net.mapeadores.util.text.LabelChange;
import net.mapeadores.util.text.RelativePath;
import net.mapeadores.util.text.StringUtils;
import net.mapeadores.util.text.tableparser.CsvParameters;
import net.mapeadores.util.text.tableparser.SheetCopyParameters;
import net.mapeadores.util.text.tableparser.TableParser;
import net.mapeadores.util.xml.DOMUtils;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;


/**
 *
 * @author Vincent Calame
 */
public abstract class AbstractUtilRequestHandler extends AbstractRequestHandler {

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

    public Comparator<FicheMeta> getComparator(Lang lang) throws ErrorMessageException {
        String sort = getTrimedParameter(InteractionConstants.SORT_PARAMNAME);
        if (sort.isEmpty()) {
            return Comparators.FICHEID_ASC;
        }
        try {
            sort = SortConstants.checkSortType(sort);
            return Comparators.getComparator(sort, lang);
        } catch (IllegalArgumentException iae) {
            throw BdfErrors.unknownParameterValue(InteractionConstants.SORT_PARAMNAME, sort);
        }
    }

    public FicheTableParameters getFicheTableParameters() throws ErrorMessageException {
        FicheTableParametersBuilder ficheTableParametersBuilder = new FicheTableParametersBuilder();
        String[] tokens = getTokens(InteractionConstants.WITH_PARAMNAME);
        for (String token : tokens) {
            ficheTableParametersBuilder.putWith(token);
        }
        String patternMode = getTrimedParameter(InteractionConstants.PATTERNMODE_PARAMNAME);
        if (!patternMode.isEmpty()) {
            try {
                ficheTableParametersBuilder.setPatternMode(patternMode);
            } catch (IllegalArgumentException iae) {
                throw new ErrorMessageException("_ error.unknown.patternmode", patternMode);
            }
        }
        return ficheTableParametersBuilder.toFicheTableParameters();
    }

    public String getHeaderType() throws ErrorMessageException {
        String headerTypeValue = getTrimedParameter(InteractionConstants.HEADERTYPE_PARAMNAME);
        if (headerTypeValue.isEmpty()) {
            return TableExportConstants.COLUMNTITLE_HEADER;
        }
        try {
            return TableExportConstants.checkHeaderType(headerTypeValue);
        } catch (IllegalArgumentException iae) {
            throw BdfErrors.unknownParameterValue(InteractionConstants.HEADERTYPE_PARAMNAME, headerTypeValue);
        }
    }

    public LabelChange getLabelChange(String paramPrefix) {
        return BdfCommandUtils.getLabelChange(requestMap, paramPrefix, true);
    }

    public LabelChange getLabelChange(String paramPrefix, boolean withTypoParsing) {
        return BdfCommandUtils.getLabelChange(requestMap, paramPrefix, withTypoParsing);
    }

    public String getMode() throws ErrorMessageException {
        String mode = requestMap.getTrimedParameter(InteractionConstants.MODE_PARAMNAME);
        if (mode.isEmpty()) {
            return "";
        }
        try {
            StringUtils.checkTechnicalName(mode, false);
        } catch (ParseException pe) {
            throw BdfErrors.error("_ error.wrong.mode", mode);
        }
        store(InteractionConstants.MODE_PARAMNAME, mode);
        return mode;
    }

    public TableParser.Parameters getTableParserParameters() throws ErrorMessageException {
        String parseType = getMandatoryParameter(InteractionConstants.PARSETYPE_PARAMNAME);
        String delimParam = getTrimedParameter(InteractionConstants.CSV_DELIMITER_PARAMNAME);
        String quoteParam = getTrimedParameter(InteractionConstants.CSV_QUOTE_PARAMNAME);
        boolean escapedCSV = isTrue(InteractionConstants.CSV_ESCAPED_PARAMNAME);
        TableParser.Parameters params = null;
        if (parseType.equals(TableParser.SHEETCOPY_PARSETYPE)) {
            params = new SheetCopyParameters();
        } else if (parseType.equals(TableParser.CSV_PARSETYPE)) {
            CsvParameters csvParameters = new CsvParameters();
            if (!delimParam.isEmpty()) {
                try {
                    char delim = StringUtils.stringToChar(delimParam);
                    csvParameters.setDelimiter(delim);
                } catch (IllegalArgumentException iae) {
                    throw BdfErrors.wrongParameterValue(InteractionConstants.CSV_DELIMITER_PARAMNAME, delimParam);
                }
            }
            if (!quoteParam.isEmpty()) {
                try {
                    char quote = StringUtils.stringToChar(quoteParam);
                    csvParameters.setQuote(quote);
                } catch (IllegalArgumentException iae) {
                    throw BdfErrors.wrongParameterValue(InteractionConstants.CSV_QUOTE_PARAMNAME, quoteParam);
                }
            }
            csvParameters.setEscapedCSV(escapedCSV);
            params = csvParameters;
        } else {
            throw BdfErrors.wrongParameterValue(InteractionConstants.PARSETYPE_PARAMNAME, parseType);
        }
        return params;
    }

    public AccessDef getMandatoryAccessDef() throws ErrorMessageException {
        String param_access = getMandatoryParameter(InteractionConstants.ACCESS_PARAMNAME);
        AccessDef accessDef = bdfServer.getAccessManager().getAccessDef(param_access);
        if (accessDef == null) {
            throw BdfErrors.unknownParameterValue(InteractionConstants.ACCESS_PARAMNAME, param_access);
        }
        return accessDef;
    }

    public Addenda getMandatoryAddenda() throws ErrorMessageException {
        return (Addenda) getMandatorySubset(SubsetKey.CATEGORY_ADDENDA);
    }

    public Album getMandatoryAlbum() throws ErrorMessageException {
        return (Album) getMandatorySubset(SubsetKey.CATEGORY_ALBUM);
    }

    public AlbumDim getMandatoryAlbumDim() throws ErrorMessageException {
        Album album = getMandatoryAlbum();
        String paramValue = getMandatoryParameter(InteractionConstants.ALBUMDIM_PARAMNAME);
        AlbumDim albumDim = album.getAlbumMetadata().getAlbumDimByName(paramValue);
        if (albumDim == null) {
            throw BdfErrors.unknownParameterValue(InteractionConstants.ALBUMDIM_PARAMNAME, paramValue);
        }
        return albumDim;
    }

    public BalayageDescription getMandatoryBalayageDescription() throws ErrorMessageException {
        String param_balayage = getMandatoryParameter(InteractionConstants.BALAYAGE_PARAMNAME);
        BalayageDescription balayageDescription = bdfServer.getBalayageManager().getBalayage(param_balayage);
        if (balayageDescription == null) {
            throw BdfErrors.unknownParameterValue(InteractionConstants.BALAYAGE_PARAMNAME, param_balayage);
        }
        return balayageDescription;
    }

    public BalayageContentDescription getMandatoryBalayageContentDescription(BalayageDescription balayageDescription) throws ErrorMessageException {
        String contentPath = getMandatoryPath();
        BalayageContentDescription description = BalayageUtils.getBalayageContentDescription(balayageDescription, contentPath);
        if (description == null) {
            throw BdfErrors.unknownParameterValue(InteractionConstants.PATH_PARAMNAME, contentPath);
        }
        return description;
    }

    public Corpus getMandatoryCorpus() throws ErrorMessageException {
        return (Corpus) getMandatorySubset(SubsetKey.CATEGORY_CORPUS);
    }

    public Document getMandatoryDocument() throws ErrorMessageException {
        return (Document) getMandatorySubsetItem(SubsetKey.CATEGORY_ADDENDA);
    }

    public FicheMeta getMandatoryFicheMeta() throws ErrorMessageException {
        return (FicheMeta) getMandatorySubsetItem(SubsetKey.CATEGORY_CORPUS);
    }

    public int getMandatoryId() throws ErrorMessageException {
        int id = getMandatoryIntegerParameter(InteractionConstants.ID_PARAMNAME);
        if (id < 1) {
            throw BdfErrors.wrongParameterValue(InteractionConstants.ID_PARAMNAME, requestMap.getParameter(InteractionConstants.ID_PARAMNAME));
        }
        return id;
    }

    public Illustration getMandatoryIllustration() throws ErrorMessageException {
        return (Illustration) getMandatorySubsetItem(SubsetKey.CATEGORY_ALBUM);
    }

    public int getMandatoryIntegerParameter(String paramName) throws ErrorMessageException {
        String paramValue = requestMap.getParameter(paramName);
        if (paramValue == null) {
            throw BdfErrors.emptyMandatoryParameter(paramName);
        }
        try {
            int value = Integer.parseInt(paramValue);
            store(paramName, String.valueOf(value));
            return value;
        } catch (NumberFormatException nfe) {
            throw BdfErrors.wrongParameterValue(paramName, paramValue);
        }
    }

    public Motcle getMandatoryMotcle() throws ErrorMessageException {
        String idString = requestMap.getParameter(InteractionConstants.IDMTCL_PARAMNAME);
        if (idString != null) {
            return getMandatoryMotcle(InteractionConstants.IDMTCL_PARAMNAME);
        }
        String idalpha = requestMap.getTrimedParameter(InteractionConstants.IDALPHA_PARAMNAME);
        if (!idalpha.isEmpty()) {
            Thesaurus thesaurus = getMandatoryThesaurus();
            if (thesaurus.isIdalphaType()) {
                Motcle motcle = thesaurus.getMotcleByIdalpha(idalpha);
                if (motcle != null) {
                    store(InteractionConstants.IDALPHA_PARAMNAME, idalpha);
                    return motcle;
                } else {
                    throw BdfErrors.wrongParameterValue(InteractionConstants.IDALPHA_PARAMNAME, idalpha);
                }
            }
        }
        return (Motcle) getMandatorySubsetItem(SubsetKey.CATEGORY_THESAURUS);
    }

    public Motcle getMandatoryMotcle(String paramName) throws ErrorMessageException {
        String idString = requestMap.getParameter(paramName);
        Thesaurus thesaurus = getMandatoryThesaurus();
        Motcle motcle = null;
        try {
            motcle = ThesaurusUtils.getMotcle(thesaurus, idString);
        } catch (NumberFormatException nfe) {
            throw BdfErrors.wrongParameterValue(paramName, idString);
        }
        if (motcle == null) {
            throw BdfErrors.unknownParameterValue(paramName, idString);
        }
        store(paramName, idString);
        return motcle;
    }

    public String getMandatoryPath() throws ErrorMessageException {
        String path = getMandatoryParameter(InteractionConstants.PATH_PARAMNAME).trim();
        if (path.isEmpty()) {
            throw BdfErrors.wrongParameterValue(InteractionConstants.PATH_PARAMNAME, path);
        }
        return path;
    }

    public RelativePath getMandatoryRelativePath() throws ErrorMessageException {
        String path = getMandatoryParameter(InteractionConstants.PATH_PARAMNAME);
        RelativePath relativePath;
        try {
            relativePath = RelativePath.parse(path);
            if (!ResourceUtils.isValidResourceRelativePath(relativePath)) {
                relativePath = null;
            }
        } catch (ParseException pe) {
            relativePath = null;
        }
        if (relativePath == null) {
            throw BdfErrors.wrongParameterValue(InteractionConstants.PATH_PARAMNAME, path);
        }
        return relativePath;
    }

    public Redacteur getMandatoryRedacteur() throws ErrorMessageException {
        return (Redacteur) getMandatorySubsetItem(SubsetKey.CATEGORY_SPHERE);
    }

    public Role getMandatoryRole() throws ErrorMessageException {
        String roleString = getMandatoryParameter(InteractionConstants.ROLE_PARAMNAME);
        Role role = bdfServer.getPermissionManager().getRole(roleString);
        if (role == null) {
            throw BdfErrors.unknownParameterValue(InteractionConstants.ROLE_PARAMNAME, roleString);
        }
        return role;
    }

    public Sphere getMandatorySphere() throws ErrorMessageException {
        return (Sphere) getMandatorySubset(SubsetKey.CATEGORY_SPHERE);
    }

    public Subset getMandatorySubset(short subsetCategory) throws ErrorMessageException {
        return getMandatorySubset(subsetCategory, SubsetKey.categoryToString(subsetCategory));
    }

    public Subset getMandatorySubset(short subsetCategory, String paramName) throws ErrorMessageException {
        String paramValue = getMandatoryParameter(paramName);
        try {
            SubsetKey subsetKey = SubsetKey.parse(subsetCategory, paramValue);
            Subset subset = getFichotheque().getSubset(subsetKey);
            if (subset == null) {
                throw BdfErrors.unknownParameterValue(paramName, paramValue);
            }
            return subset;
        } catch (ParseException pe) {
            throw BdfErrors.wrongParameterValue(paramName, paramValue);
        }
    }

    public Subset getMandatorySubset() throws ErrorMessageException {
        return getMandatorySubset(InteractionConstants.SUBSET_PARAMNAME);
    }

    public Subset getMandatorySubset(String paramName) throws ErrorMessageException {
        String paramValue = getMandatoryParameter(paramName);
        try {
            SubsetKey subsetKey = SubsetKey.parse(paramValue);
            Subset subset = getFichotheque().getSubset(subsetKey);
            if (subset == null) {
                throw BdfErrors.unknownParameterValue(paramName, paramValue);
            }
            return subset;
        } catch (ParseException pe) {
            throw BdfErrors.wrongParameterValue(paramName, paramValue);
        }
    }

    public SubsetItem getMandatorySubsetItem(short subsetCategory) throws ErrorMessageException {
        int id = getMandatoryId();
        Subset subset = getMandatorySubset(subsetCategory);
        SubsetItem subsetItem = subset.getSubsetItemById(id);
        if (subsetItem == null) {
            throw BdfErrors.unknownParameterValue(InteractionConstants.ID_PARAMNAME, String.valueOf(id));
        }
        return subsetItem;
    }

    public ScrutariExportDef getMandatoryScrutariExportDef() throws ErrorMessageException {
        String scrutariexportString = getMandatoryParameter(InteractionConstants.SCRUTARIEXPORT_PARAMNAME);
        ScrutariExportDef scrutariExportDef = bdfServer.getScrutariExportManager().getScrutariExportDef(scrutariexportString);
        if (scrutariExportDef == null) {
            throw BdfErrors.unknownParameterValue(InteractionConstants.SCRUTARIEXPORT_PARAMNAME, scrutariexportString);
        }
        return scrutariExportDef;
    }

    public SelectionDef getMandatorySelectionDef() throws ErrorMessageException {
        String param_selection = getMandatoryParameter(InteractionConstants.SELECTION_PARAMNAME);
        SelectionDef selectionDef = bdfServer.getSelectionManager().getSelectionDef(param_selection);
        if (selectionDef == null) {
            throw BdfErrors.unknownParameterValue(InteractionConstants.SELECTION_PARAMNAME, param_selection);
        }
        return selectionDef;
    }

    public SqlExportDef getMandatorySqlExportDef() throws ErrorMessageException {
        String param_sqlexport = getMandatoryParameter(InteractionConstants.SQLEXPORT_PARAMNAME);
        SqlExportDef sqlExportDef = bdfServer.getSqlExportManager().getSqlExportDef(param_sqlexport);
        if (sqlExportDef == null) {
            throw BdfErrors.unknownParameterValue(InteractionConstants.SQLEXPORT_PARAMNAME, param_sqlexport);
        }
        return sqlExportDef;
    }

    public SubsetItem getMandatorySubsetItem(Subset subset) throws ErrorMessageException {
        int id = getMandatoryId();
        SubsetItem subsetItem = subset.getSubsetItemById(id);
        if (subsetItem == null) {
            throw BdfErrors.unknownParameterValue(InteractionConstants.ID_PARAMNAME, String.valueOf(id));
        }
        return subsetItem;
    }


    public TableExportDescription getMandatoryTableExportDescription() throws ErrorMessageException {
        TableExportManager tableExportManager = bdfServer.getTableExportManager();
        String tableExportName = getMandatoryParameter(InteractionConstants.TABLEEXPORT_PARAMNAME);
        for (TableExportDescription tableExportDescription : tableExportManager.getTableExportDescriptionList()) {
            if (tableExportDescription.getName().equals(tableExportName)) {
                return tableExportDescription;
            }
        }
        throw BdfErrors.unknownParameterValue(InteractionConstants.TABLEEXPORT_PARAMNAME, tableExportName);
    }

    public TableExportContentDescription getMandatoryTableExportContentDescription(TableExportDescription tableExportDescription) throws ErrorMessageException {
        String contentPath = getMandatoryPath();
        TableExportContentDescription description = TableExportUtils.getTableExportContentDescription(tableExportDescription, contentPath);
        if (description == null) {
            throw BdfErrors.unknownParameterValue(InteractionConstants.PATH_PARAMNAME, contentPath);
        }
        return description;
    }

    public TemplateDescription getMandatoryTemplateDescription() throws ErrorMessageException {
        TransformationManager transformationManager = bdfServer.getTransformationManager();
        String templateKeyString = getMandatoryParameter(InteractionConstants.TEMPLATE_PARAMNAME);
        TemplateKey templateKey;
        try {
            templateKey = TemplateKey.parse(templateKeyString);
        } catch (ParseException pe) {
            throw BdfErrors.unknownParameterValue(InteractionConstants.TEMPLATE_PARAMNAME, templateKeyString);
        }
        TemplateDescription templateDescription = BdfTransformationUtils.getTemplateDescription(transformationManager, templateKey);
        if (templateDescription == null) {
            throw BdfErrors.unknownParameterValue(InteractionConstants.TEMPLATE_PARAMNAME, templateKeyString);
        } else {
            return templateDescription;
        }
    }

    public TemplateContentDescription getMandatoryTemplateContentDescription(TemplateDescription templateDescription) throws ErrorMessageException {
        String contentPath = getMandatoryPath();
        TemplateContentDescription description = templateDescription.getTemplateContentDescription(contentPath);
        if (description == null) {
            throw BdfErrors.unknownParameterValue(InteractionConstants.PATH_PARAMNAME, contentPath);
        }
        return description;
    }

    public Thesaurus getMandatoryThesaurus() throws ErrorMessageException {
        return (Thesaurus) getMandatorySubset(SubsetKey.CATEGORY_THESAURUS);
    }

    public TransformationDescription getMandatoryTransformationDescription() throws ErrorMessageException {
        TransformationManager transformationManager = bdfServer.getTransformationManager();
        String s = getMandatoryParameter(InteractionConstants.TRANSFORMATION_PARAMNAME);
        try {
            TransformationKey transformationKey = TransformationKey.parse(s);
            return transformationManager.getTransformationDescription(transformationKey);
        } catch (ParseException pe) {
            throw BdfErrors.wrongParameterValue(InteractionConstants.TRANSFORMATION_PARAMNAME, s);
        }
    }

    public Motcle getOptionnalMotcle(Thesaurus thesaurus) throws ErrorMessageException {
        String idmtclValue = requestMap.getParameter(InteractionConstants.IDMTCL_PARAMNAME);
        if (idmtclValue == null) {
            return (Motcle) getOptionnalSubsetItem(thesaurus);
        }
        try {
            Motcle motcle = ThesaurusUtils.getMotcle(thesaurus, idmtclValue);
            store(InteractionConstants.IDMTCL_PARAMNAME, idmtclValue);
            return motcle;
        } catch (NumberFormatException nfe) {
            throw BdfErrors.wrongParameterValue(InteractionConstants.IDMTCL_PARAMNAME, idmtclValue);
        }
    }

    public SubsetItem getOptionnalSubsetItem(Subset subset) throws ErrorMessageException {
        return getOptionnalSubsetItem(subset, InteractionConstants.ID_PARAMNAME);
    }

    public SubsetItem getOptionnalSubsetItem(Subset subset, String paramName) throws ErrorMessageException {
        String idString = requestMap.getParameter(paramName);
        if (idString == null) {
            return null;
        }
        int id = 0;
        try {
            id = Integer.parseInt(idString);
        } catch (NumberFormatException nfe) {
            throw BdfErrors.wrongParameterValue(paramName, idString);
        }
        if (id < 1) {
            throw BdfErrors.wrongParameterValue(paramName, idString);
        }
        SubsetItem subsetItem = subset.getSubsetItemById(id);
        store(paramName, String.valueOf(id));
        return subsetItem;
    }

    public FicheSelectorBuilder populate(FicheSelectorBuilder builder) throws ErrorMessageException {
        if (hasParameter(InteractionConstants.SELECTION_PARAMNAME)) {
            return populateFromSelection(builder);
        } else {
            return populateFromXml(builder);
        }
    }

    public FicheSelectorBuilder populateFromSelection(FicheSelectorBuilder builder) throws ErrorMessageException {
        SelectionDef selectionDef = getMandatorySelectionDef();
        for (FicheQuery ficheQuery : selectionDef.getFichothequeQueries().getFicheQueryList()) {
            builder.add(ficheQuery);
        }
        return builder;
    }

    public FicheSelectorBuilder populateFromXml(FicheSelectorBuilder builder) throws ErrorMessageException {
        String xml = getMandatoryParameter(InteractionConstants.XML_PARAMNAME);
        xml = xml.trim();
        if (xml.length() == 0) {
            throw BdfErrors.wrongParameterValue(InteractionConstants.XML_PARAMNAME, "");
        }
        org.w3c.dom.Document document;
        try {
            document = DOMUtils.parseDocument(xml);
        } catch (SAXException sae) {
            throw BdfErrors.error("_ error.exception.xml.sax", sae.getMessage());
        }
        Element root = document.getDocumentElement();
        switch (root.getTagName()) {
            case "fiche-query":
            case "fiche-select":
                FicheQuery ficheQuery = SelectionDOMUtils.getFicheConditionEntry(bdfServer.getFichotheque(), root).getFicheQuery();
                builder.add(ficheQuery);
                break;
            default:
                FichothequeQueriesBuilder fichothequeQueriesBuilder = new FichothequeQueriesBuilder();
                DOMUtils.readChildren(root, SelectionDOMUtils.getQueryElementConsumer(bdfServer.getFichotheque(), fichothequeQueriesBuilder));
                FichothequeQueries fichothequeQueries = fichothequeQueriesBuilder.toFichothequeQueries();
                if (fichothequeQueries.getFicheQueryList().isEmpty()) {
                    throw new ErrorMessageException("_ error.wrong.fql.nofichequery");
                }
                for (FicheQuery fq : fichothequeQueries.getFicheQueryList()) {
                    builder.add(fq);
                }
        }
        return builder;
    }

    public MotcleSelectorBuilder populateFromXml(MotcleSelectorBuilder builder) throws ErrorMessageException {
        String xml = getMandatoryParameter(InteractionConstants.XML_PARAMNAME);
        org.w3c.dom.Document document;
        try {
            document = DOMUtils.parseDocument(xml);
        } catch (SAXException sae) {
            throw BdfErrors.error("_ error.exception.xml.sax", sae.getMessage());
        }
        Element root = document.getDocumentElement();
        switch (root.getTagName()) {
            case "motcle-query":
            case "motcle-select":
                MotcleQuery motcleQuery = SelectionDOMUtils.getMotcleConditionEntry(bdfServer.getFichotheque(), root).getMotcleQuery();
                builder.add(motcleQuery);
                break;
            default:
                FichothequeQueriesBuilder fichothequeQueriesBuilder = new FichothequeQueriesBuilder();
                DOMUtils.readChildren(root, SelectionDOMUtils.getQueryElementConsumer(bdfServer.getFichotheque(), fichothequeQueriesBuilder));
                FichothequeQueries fichothequeQueries = fichothequeQueriesBuilder.toFichothequeQueries();
                if (fichothequeQueries.getMotcleQueryList().isEmpty()) {
                    throw BdfErrors.unsupportedParameterValue(InteractionConstants.XML_PARAMNAME, "Missing fiche-query elements");
                }
                for (MotcleQuery mq : fichothequeQueries.getMotcleQueryList()) {
                    builder.add(mq);
                }
        }
        return builder;
    }

}
