/* FichothequeLib_Tools - Copyright (c) 2012-2021 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.formatters;

import net.fichotheque.format.FormatSource;
import net.fichotheque.format.formatters.ValueFormatter;
import net.fichotheque.tools.format.patterndefs.DefaultPattern;
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 ValueFormatterParser {

    private final static ValueFormatter VALUE_PART = (value, formatSource) -> {
        return value;
    };
    private final static ValueFormatter VALUE_UP_PART = (value, formatSource) -> {
        return FormatterParserUtils.toUppercase(value, formatSource);
    };

    private ValueFormatterParser() {
    }

    public static ValueFormatter parse(String pattern, InstructionResolverProvider provider, MessageHandler messageHandler) {
        if (pattern == null) {
            pattern = DefaultPattern.value();
        }
        try {
            return parse(pattern, provider);
        } catch (ErrorMessageException fe) {
            messageHandler.addMessage(FormatConstants.SEVERE_PATTERN, fe.getErrorMessage());
            return null;
        }
    }

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

    public static boolean withToUppercaseInstruction(Instruction instruction) {
        for (Argument argument : instruction) {
            String key = argument.getKey();
            if (key.equals("up")) {
                return true;
            }
        }
        return false;
    }


    private static class InternalValueFormatter implements ValueFormatter {

        private final Object[] partArray;

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

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

    }


    private static class InternalInstructionResolver implements InstructionResolver {

        private final InstructionResolverProvider provider;

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

        @Override
        public Object resolve(Instruction instruction) throws ErrorMessageException {
            InstructionResolver resolver = provider.getInstructionResolver(ValueFormatter.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":
                    return VALUE_PART;
                case "value": {
                    if (FormatterParserUtils.isUppercase(instruction)) {
                        return VALUE_UP_PART;
                    } else {
                        return VALUE_PART;
                    }
                }
                default:
                    return null;
            }
        }

    }


}
