/* BdfServer - 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.tools.instruction;

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.api.instruction.BdfParameters;
import java.text.ParseException;
import java.util.Map;
import net.fichotheque.Fichotheque;
import net.fichotheque.corpus.Corpus;
import net.fichotheque.extraction.ExtractionContext;
import net.fichotheque.format.FormatContext;
import net.fichotheque.tools.corpus.FieldGenerationEngine;
import net.fichotheque.tools.parsers.TypoParser;
import net.fichotheque.tools.selection.FichothequeQueriesBuilder;
import net.fichotheque.tools.selection.SelectionDOMUtils;
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.LabelChangeBuilder;
import net.mapeadores.util.text.TypoOptions;
import net.mapeadores.util.xml.DOMUtils;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;


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

    public final static String PHRASE_PARAMSTART = "phrase_";

    private BdfCommandUtils() {
    }

    public static LabelChange getLabelChange(RequestMap requestMap, String paramPrefix, boolean withTypoParsing) {
        LabelChangeBuilder result = new LabelChangeBuilder();
        int prefixLength = paramPrefix.length();
        for (String paramName : requestMap.getParameterNameSet()) {
            if (!paramName.startsWith(paramPrefix)) {
                continue;
            }
            try {
                Lang currentLang = Lang.parse(paramName.substring(prefixLength));
                String newLabelString = requestMap.getParameter(paramName);
                if (withTypoParsing) {
                    TypoOptions typoOptions = TypoOptions.getTypoOptions(currentLang.toLocale());
                    newLabelString = TypoParser.parseTypo(newLabelString, typoOptions);
                }
                result.putLabel(currentLang, newLabelString);

            } catch (ParseException pe) {
            }
        }
        return result.toLabelChange();
    }

    public static void populatePhraseLabelChange(RequestMap requestMap, Map<String, LabelChange> phraseChangeMap) {
        for (String paramName : requestMap.getParameterNameSet()) {
            if (paramName.startsWith(PHRASE_PARAMSTART)) {
                String phraseName = paramName.substring(PHRASE_PARAMSTART.length());
                int idx = phraseName.indexOf('/');
                if (idx > 0) {
                    phraseName = phraseName.substring(0, idx);
                    LabelChange phraseChange = BdfCommandUtils.getLabelChange(requestMap, BdfInstructionUtils.getPhraseParamPrefix(phraseName), true);
                    phraseChangeMap.put(phraseName, phraseChange);
                }
            }
        }
    }

    public static FieldGenerationEngine buildEngine(BdfParameters bdfParameters, Corpus corpus) {
        BdfServer bdfServer = bdfParameters.getBdfServer();
        ExtractionContext extractionContext = bdfParameters.getDefaultExtractionContext();
        FormatContext formatContext = bdfServer.getFormatContext();
        Lang defaultLang = bdfServer.getDefaultWorkingLang();
        return FieldGenerationEngine.build(corpus, extractionContext, formatContext, defaultLang);
    }

    public static void parseQueries(Fichotheque fichotheque, String queryXml, FichothequeQueriesBuilder queriesBuilder) throws ErrorMessageException {
        queryXml = queryXml.trim();
        if (queryXml.isEmpty()) {
            return;
        }
        queryXml = "<queries>" + queryXml + "</queries>";
        try {
            Document document = DOMUtils.parseDocument(queryXml);
            DOMUtils.readChildren(document.getDocumentElement(), SelectionDOMUtils.getQueryElementConsumer(fichotheque, queriesBuilder));
        } catch (SAXException saxException) {
            throw BdfErrors.error("_ error.wrong.queryxml", saxException.getMessage());
        }
    }

}
