/* FichothequeLib_Tools  - Copyright (c) 2007-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 net.fichotheque.tools.format.parsers;

import net.fichotheque.format.FormatSource;
import net.fichotheque.format.formatters.MotcleFormatter;
import net.fichotheque.thesaurus.Motcle;
import net.fichotheque.tools.format.DefaultPatternCatalog;
import net.fichotheque.tools.format.JsonParameters;
import net.fichotheque.tools.format.LangParameters;
import net.fichotheque.tools.format.catalogs.MotcleFormatterCatalog;
import net.fichotheque.utils.FormatterUtils;
import net.mapeadores.util.format.FormatConstants;
import net.mapeadores.util.instruction.Argument;
import net.mapeadores.util.instruction.Instruction;
import net.mapeadores.util.instruction.InstructionResolver;
import net.mapeadores.util.instruction.InstructionResolverProvider;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.logging.MessageHandler;


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

    private final static JsonParameters DEFAULT_JSONPARAMETERS = JsonParameters.build("type", "id", "idalpha");

    private MotcleFormatterParser() {
    }

    public static MotcleFormatter parse(boolean isIdalpha, String pattern, InstructionResolverProvider provider, boolean withWeightFilter, MessageHandler messageHandler) {
        if (pattern == null) {
            pattern = DefaultPatternCatalog.motcle(isIdalpha);
        }
        try {
            return MotcleFormatterParser.parse(pattern, provider, withWeightFilter);
        } catch (ErrorMessageException fe) {
            messageHandler.addMessage(FormatConstants.SEVERE_PATTERN, fe.getErrorMessage());
            return null;
        }
    }

    public static MotcleFormatter parse(String pattern, InstructionResolverProvider provider, boolean withhWeightFilter) throws ErrorMessageException {
        Object[] partArray = FormatterUtils.parsePattern(new InternalInstructionResolver(provider, withhWeightFilter), pattern);
        return new InternalMotcleFormatter(partArray);
    }


    private static class InternalMotcleFormatter implements MotcleFormatter {

        private final Object[] partArray;

        private InternalMotcleFormatter(Object[] partArray) {
            this.partArray = partArray;
        }

        @Override
        public String formatMotcle(Motcle motcle, int weight, FormatSource formatSource) {
            StringBuilder buf = new StringBuilder();
            int length = partArray.length;
            for (int i = 0; i < length; i++) {
                Object obj = partArray[i];
                if (obj instanceof String) {
                    buf.append((String) obj);
                    continue;
                }
                MotcleFormatter formatter = (MotcleFormatter) obj;
                buf.append(formatter.formatMotcle(motcle, weight, formatSource));
            }
            return buf.toString();
        }

    }


    private static class InternalInstructionResolver implements InstructionResolver {

        private final InstructionResolverProvider provider;
        private final boolean withWeightFilter;

        private InternalInstructionResolver(InstructionResolverProvider provider, boolean withWeightFilter) {
            this.provider = provider;
            this.withWeightFilter = withWeightFilter;
        }

        @Override
        public Object resolve(Instruction instruction) throws ErrorMessageException {
            InstructionResolver resolver = provider.getInstructionResolver(MotcleFormatter.class);
            if (resolver != null) {
                Object formatter = resolver.resolve(instruction);
                if (formatter != null) {
                    return formatter;
                }
            }
            Argument arg1 = instruction.get(0);
            String key = arg1.getKey();
            String value = arg1.getNotNullValue();
            switch (key) {
                case "formsyntax": {
                    if (withWeightFilter) {
                        return MotcleFormatterCatalog.WITHWEIGHTFILTER_FORMSYNTAX_FORMATTER;
                    } else {
                        return MotcleFormatterCatalog.WITHOUTWEIGHTFILTER_FORMSYNTAX_FORMATTER;
                    }
                }
                case "idalpha": {
                    switch (value) {
                        case "significant":
                            return MotcleFormatterCatalog.IDALPHA_SIGNIFICANT;
                        default:
                            return MotcleFormatterCatalog.IDALPHA;
                    }
                }
                case "idalpha_significant":
                    return MotcleFormatterCatalog.IDALPHA_SIGNIFICANT;
                case "id":
                case "idths":
                    return MotcleFormatterCatalog.ID;
                case "json": {
                    JsonParameters jsonParameters = JsonParameters.fromInstruction(instruction, DEFAULT_JSONPARAMETERS);
                    LangParameters langParameters = LangParameters.fromInstruction(instruction, "langs");
                    return new MotcleFormatterCatalog.Json(jsonParameters, langParameters.getCustomLangContext());
                }
                case "label":
                case "lib":
                    return new MotcleFormatterCatalog.Label(LangParameters.fromInstruction(instruction, key));
                case "lang":
                    return MotcleFormatterCatalog.LANG;
                case "weight":
                case "poids":
                    return MotcleFormatterCatalog.WEIGHT;
                case "position":
                    switch (value) {
                        case "global":
                            return MotcleFormatterCatalog.POSITION_GLOBAL;
                        default:
                            return MotcleFormatterCatalog.POSITION;
                    }
                case "pos_loc":
                    return MotcleFormatterCatalog.POSITION;
                case "pos_glob":
                    return MotcleFormatterCatalog.POSITION_GLOBAL;
                case "parent_id":
                case "parent_idths":
                    return MotcleFormatterCatalog.PARENT_ID;
                case "parent_idalpha":
                    switch (value) {
                        case "significant":
                            return MotcleFormatterCatalog.PARENT_IDALPHA_SIGNIFICANT;
                        default:
                            return MotcleFormatterCatalog.PARENT_IDALPHA;
                    }
                case "parent_idalpha_significant":
                    return MotcleFormatterCatalog.PARENT_IDALPHA_SIGNIFICANT;
                case "thesaurus":
                    return MotcleFormatterCatalog.THESAURUS;
                default:
                    return null;
            }
        }

    }


}
