/* FichothequeLib_Tools - 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 net.fichotheque.tools.format.parsers;

import net.fichotheque.format.FormatContext;
import net.fichotheque.format.FormatSource;
import net.fichotheque.format.formatters.ExtractionFormatter;
import net.fichotheque.tools.format.DefaultPatternCatalog;
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.logging.ErrorMessageException;
import net.mapeadores.util.logging.MessageHandler;


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

    private ExtractionFormatterParser() {
    }

    public static ExtractionFormatter parse(String pattern, FormatContext formatContext, MessageHandler messageHandler) {
        if (pattern == null) {
            pattern = DefaultPatternCatalog.EXTRACTION;
        }
        try {
            return parse(pattern, formatContext);
        } catch (ErrorMessageException fe) {
            messageHandler.addMessage(FormatConstants.SEVERE_PATTERN, fe.getErrorMessage());
            return null;
        }
    }

    public static ExtractionFormatter parse(String pattern, FormatContext formatContext) throws ErrorMessageException {
        Object[] partArray = FormatterUtils.parsePattern(new InternalInstructionResolver(formatContext), pattern);
        return new InternalExtractionFormatter(partArray);
    }


    private static class InternalExtractionFormatter implements ExtractionFormatter {

        private final Object[] partArray;

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

        @Override
        public String formatExtraction(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;
                }
                ExtractionFormatter formatter = (ExtractionFormatter) obj;
                buf.append(formatter.formatExtraction(formatSource));
            }
            return buf.toString();
        }

    }


    private static class InternalInstructionResolver implements InstructionResolver {

        private final FormatContext formatContext;

        private InternalInstructionResolver(FormatContext formatContext) {
            this.formatContext = formatContext;
        }

        @Override
        public Object resolve(Instruction instruction) throws ErrorMessageException {
            InstructionResolver resolver = formatContext.getInstructionResolverProvider().getInstructionResolver(ExtractionFormatter.class);
            if (resolver != null) {
                Object formatter = resolver.resolve(instruction);
                if (formatter != null) {
                    return formatter;
                }
            }
            Argument arg1 = instruction.get(0);
            String key = arg1.getKey();
            switch (key) {
                case "formsyntax":
                case "xml":
                    return formatContext.getExtractionFormatter(null, instruction.toOptionMap(1));
                case "transformation":
                case "xslt":
                    String name = arg1.getValue();
                    ExtractionFormatter extractionFormatter = formatContext.getExtractionFormatter(name, instruction.toOptionMap(1));
                    if (extractionFormatter == null) {
                        throw new ErrorMessageException("_ error.unknown.template", name);
                    }
                    return extractionFormatter;
                default:
                    return null;
            }
        }

    }

}
