/* FichothequeLib_Tools - Copyright (c) 2015-2020 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.FormatContext;
import net.fichotheque.format.FormatSource;
import net.fichotheque.format.formatters.AttributeFormatter;
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 AttributeFormatterParser {

    private final static AttributeFormatter VALUE_PART = (attributeValue, valueIndex, formatSource) -> {
        return attributeValue;
    };
    private final static AttributeFormatter FORMSYNTAX_PART = new FormSyntaxPart();

    private AttributeFormatterParser() {

    }

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

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


    private static class InternalAttributeFormatter implements AttributeFormatter {

        private final Object[] partArray;

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

        @Override
        public String formatAttributeValue(String attributeValue, int valueIndex, 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;
                }
                AttributeFormatter formatter = (AttributeFormatter) obj;
                buf.append(formatter.formatAttributeValue(attributeValue, valueIndex, formatSource));
            }
            return buf.toString();
        }

    }


    private static class InternalInstructionResolver implements InstructionResolver {

        private final InstructionResolverProvider provider;

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

        @Override
        public Object resolve(Instruction instruction) throws ErrorMessageException {
            InstructionResolver resolver = provider.getInstructionResolver(net.fichotheque.format.formatters.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 FORMSYNTAX_PART;
                case "value":
                    return VALUE_PART;
                default:
                    return null;
            }
        }

    }


    private static class FormSyntaxPart implements AttributeFormatter {

        private FormSyntaxPart() {

        }

        @Override
        public String formatAttributeValue(String attributeValue, int valueIndex, FormatSource formatSource) {
            int length = attributeValue.length();
            StringBuilder buf = new StringBuilder(length + 20);
            for (int i = 0; i < length; i++) {
                char carac = attributeValue.charAt(i);
                switch (carac) {
                    case ';':
                        buf.append("\\;");
                        break;
                    case '\\':
                        buf.append("\\\\");
                        break;
                    default:
                        buf.append(carac);
                        break;
                }
            }
            return buf.toString();
        }

    }

}
