/* FichothequeLib_Tools  - Copyright (c) 2007-2022 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 java.io.IOException;
import net.fichotheque.exportation.table.Cell;
import net.fichotheque.format.FormatSource;
import net.fichotheque.format.formatters.MotcleFormatter;
import net.fichotheque.json.MotcleJson;
import net.fichotheque.thesaurus.Motcle;
import net.fichotheque.tools.format.patterndefs.DefaultPattern;
import net.fichotheque.utils.FormatterUtils;
import net.fichotheque.utils.ThesaurusUtils;
import net.mapeadores.util.exceptions.ShouldNotOccurException;
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.json.JSONWriter;
import net.mapeadores.util.localisation.Lang;
import net.mapeadores.util.localisation.LangContext;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.logging.MessageHandler;
import net.mapeadores.util.text.Label;


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

    private final static MotcleFormatter ID_PART = (motcle, weight, formatSource) -> {
        return String.valueOf(motcle.getId());
    };
    private final static MotcleFormatter IDALPHA_PART = (motcle, weight, formatSource) -> {
        String idalpha = motcle.getIdalpha();
        if (idalpha == null) {
            idalpha = "";
        }
        return idalpha;
    };
    private final static MotcleFormatter IDALPHA_SIGNIFICANT_PART = (motcle, weight, formatSource) -> {
        String idalpha = motcle.getSignificantIdalpha();
        if (idalpha == null) {
            idalpha = "";
        }
        return idalpha;
    };
    private final static MotcleFormatter LANG_PART = (motcle, weight, formatSource) -> {
        if (!motcle.isBabelienType()) {
            return "";
        }
        Label label = motcle.getBabelienLabel();
        return label.getLang().toString();
    };
    private final static MotcleFormatter WEIGHT_PART = (motcle, weight, formatSource) -> {
        return String.valueOf(weight);
    };
    private final static MotcleFormatter PARENT_ID_PART = (motcle, weight, formatSource) -> {
        Motcle parent = motcle.getParent();
        if (parent != null) {
            return String.valueOf(parent.getId());
        } else {
            return "";
        }
    };
    private final static MotcleFormatter PARENT_IDALPHA_PART = (motcle, weight, formatSource) -> {
        String idalpha = null;
        Motcle parentMotcle = motcle.getParent();
        if (parentMotcle != null) {
            idalpha = parentMotcle.getIdalpha();
        }
        if (idalpha == null) {
            idalpha = "";
        }
        return idalpha;
    };
    private final static MotcleFormatter PARENT_IDALPHA_SIGNIFICANT_PART = (motcle, weight, formatSource) -> {
        String idalpha = null;
        Motcle parentMotcle = motcle.getParent();
        if (parentMotcle != null) {
            idalpha = parentMotcle.getSignificantIdalpha();
        }
        if (idalpha == null) {
            idalpha = "";
        }
        return idalpha;
    };
    private final static MotcleFormatter POSITION_PART = (motcle, weight, formatSource) -> {
        return String.valueOf(motcle.getChildIndex() + 1);
    };
    private final static MotcleFormatter POSITION_GLOBAL_PART = (motcle, weight, formatSource) -> {
        return ThesaurusUtils.getGlobalPosition(motcle);
    };
    private final static MotcleFormatter THESAURUS_PART = (motcle, weight, formatSource) -> {
        return motcle.getSubsetName();
    };
    private final static MotcleFormatter WITHWEIGHTFILTER_FORMSYNTAX_FORMATTER = new FormSyntaxPart(true);
    private final static MotcleFormatter WITHOUTWEIGHTFILTER_FORMSYNTAX_FORMATTER = new FormSyntaxPart(false);
    private final static JsonParameters DEFAULT_JSONPARAMETERS = JsonParameters.parse("labels");

    private MotcleFormatterParser() {
    }

    public static MotcleFormatter parse(boolean isIdalpha, String pattern, InstructionResolverProvider provider, boolean withWeightFilter, MessageHandler messageHandler) {
        if (pattern == null) {
            pattern = DefaultPattern.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.getValue();
            if (value == null) {
                value = "";
            }
            switch (key) {
                case "formsyntax": {
                    if (withWeightFilter) {
                        return WITHWEIGHTFILTER_FORMSYNTAX_FORMATTER;
                    } else {
                        return WITHOUTWEIGHTFILTER_FORMSYNTAX_FORMATTER;
                    }
                }
                case "idalpha": {
                    switch (value) {
                        case "significant":
                            return IDALPHA_SIGNIFICANT_PART;
                        default:
                            return IDALPHA_PART;
                    }
                }
                case "idalpha_significant":
                    return IDALPHA_SIGNIFICANT_PART;
                case "id":
                case "idths":
                    return ID_PART;
                case "json": {
                    JsonParameters jsonParameters = JsonParameters.fromInstruction(instruction);
                    if (jsonParameters == null) {
                        jsonParameters = DEFAULT_JSONPARAMETERS;
                    }
                    LangParameters langParameters = LangParameters.fromInstruction(instruction, "langs");
                    return new JsonPart(jsonParameters, langParameters.getCustomLangContext());
                }
                case "label":
                case "lib":
                    return new LabelPart(LangParameters.fromInstruction(instruction, key));
                case "lang":
                    return LANG_PART;
                case "weight":
                case "poids":
                    return WEIGHT_PART;
                case "position":
                    switch (value) {
                        case "global":
                            return POSITION_GLOBAL_PART;
                        default:
                            return POSITION_PART;
                    }
                case "pos_loc":
                    return POSITION_PART;
                case "pos_glob":
                    return POSITION_GLOBAL_PART;
                case "parent_id":
                case "parent_idths":
                    return PARENT_ID_PART;
                case "parent_idalpha":
                    switch (value) {
                        case "significant":
                            return PARENT_IDALPHA_SIGNIFICANT_PART;
                        default:
                            return PARENT_IDALPHA_PART;
                    }
                case "parent_idalpha_significant":
                    return PARENT_IDALPHA_SIGNIFICANT_PART;
                case "thesaurus":
                    return THESAURUS_PART;
                default:
                    return null;
            }
        }

    }


    private static class LabelPart implements MotcleFormatter {

        private final LangParameters langParameters;

        private LabelPart(LangParameters langParameters) {
            this.langParameters = langParameters;
        }

        @Override
        public String formatMotcle(Motcle motcle, int weight, FormatSource formatSource) {
            StringBuilder buf = new StringBuilder();
            Lang[] array = LangParameters.checkLangArray(langParameters, formatSource);
            for (Lang lang : array) {
                Label label = motcle.getLabels().getLangPartCheckedLabel(lang);
                if (label != null) {
                    if (buf.length() > 0) {
                        buf.append(langParameters.getSeparator());
                    }
                    buf.append(label.getLabelString());
                }
            }
            return buf.toString();
        }

    }


    private static class FormSyntaxPart implements MotcleFormatter {

        private final boolean withWeightFilter;

        private FormSyntaxPart(boolean withWeightFilter) {
            this.withWeightFilter = withWeightFilter;
        }

        @Override
        public String formatMotcle(Motcle motcle, int weight, FormatSource formatSource) {
            if ((withWeightFilter) || (weight == 1)) {
                String idalpha = motcle.getIdalpha();
                if (idalpha != null) {
                    return idalpha;
                } else {
                    return String.valueOf(motcle.getId());
                }
            } else {
                StringBuilder buf = new StringBuilder();
                String idalpha = motcle.getIdalpha();
                if (idalpha != null) {
                    buf.append(idalpha);
                } else {
                    buf.append(String.valueOf(motcle.getId()));
                }
                buf.append(" <");
                buf.append(weight);
                buf.append(">");
                return buf.toString();
            }
        }

    }


    private static class JsonPart implements MotcleFormatter {

        private final JsonParameters jsonParameters;
        private final LangContext customLangContext;

        private JsonPart(JsonParameters jsonParameters, LangContext customLangContext) {
            this.jsonParameters = jsonParameters;
            this.customLangContext = customLangContext;
        }

        @Override
        public String formatMotcle(Motcle motcle, int weight, FormatSource formatSource) {
            Cell[] cellArray = FormatterParserUtils.resolve(motcle, jsonParameters, formatSource);
            LangContext langContext;
            if (customLangContext != null) {
                langContext = customLangContext;
            } else {
                langContext = formatSource.getLangContext();
            }
            StringBuilder buf = new StringBuilder();
            JSONWriter jsonWriter = new JSONWriter(buf);
            try {
                jsonWriter.object();
                MotcleJson.properties(jsonWriter, motcle, langContext, jsonParameters, cellArray);
                jsonWriter.endObject();
            } catch (IOException ioe) {
                throw new ShouldNotOccurException(ioe);
            }
            return buf.toString();
        }

    }

}
