/* 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.formatters;

import java.io.IOException;
import net.fichotheque.corpus.FicheMeta;
import net.fichotheque.exportation.table.Cell;
import net.fichotheque.format.FormatContext;
import net.fichotheque.format.FormatSource;
import net.fichotheque.format.formatters.FicheMetaFormatter;
import net.fichotheque.json.FicheMetaJson;
import net.fichotheque.tools.format.patterndefs.DefaultPattern;
import net.fichotheque.utils.FormatterUtils;
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.logging.ErrorMessageException;
import net.mapeadores.util.logging.MessageHandler;


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

    private final static FicheMetaFormatter CORPUS_PART = (ficheMeta, weight, formatSource) -> {
        return ficheMeta.getSubsetName();
    };
    private final static FicheMetaFormatter ID_PART = (ficheMeta, weight, formatSource) -> {
        return String.valueOf(ficheMeta.getId());
    };
    private final static FicheMetaFormatter LANG_PART = (ficheMeta, weight, formatSource) -> {
        Lang lang = ficheMeta.getLang();
        if (lang != null) {
            return lang.toString();
        } else {
            return "";
        }
    };
    private final static FicheMetaFormatter WEIGHT_PART = (ficheMeta, weight, formatSource) -> {
        return String.valueOf(weight);
    };
    private final static FicheMetaFormatter TITLE_PART = (ficheMeta, weight, formatSource) -> {
        return ficheMeta.getTitle();
    };
    private final static JsonParameters DEFAULT_JSONPARAMETERS = JsonParameters.parse("lang");

    private FicheMetaFormatterParser() {
    }

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

    public static FicheMetaFormatter parse(String pattern, FormatContext formatContext, boolean withWeightFilter, boolean withCorpusName) throws ErrorMessageException {
        Object[] partArray = FormatterUtils.parsePattern(new InternalInstructionResolver(formatContext, withWeightFilter, withCorpusName), pattern);
        return new InternalFicheMetaFormatter(partArray);
    }


    private static class InternalFicheMetaFormatter implements FicheMetaFormatter {

        private final Object[] partArray;

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

        @Override
        public String formatFicheMeta(FicheMeta ficheMeta, 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;
                }
                FicheMetaFormatter formatter = (FicheMetaFormatter) obj;
                buf.append(formatter.formatFicheMeta(ficheMeta, weight, formatSource));
            }
            return buf.toString();
        }

    }


    private static class InternalInstructionResolver implements InstructionResolver {

        private final InstructionResolverProvider provider;
        private final boolean withWeightFilter;
        private final boolean withCorpusName;


        private InternalInstructionResolver(FormatContext formatContext, boolean withWeightFilter, boolean withCorpusName) {
            this.provider = formatContext.getInstructionResolverProvider();
            this.withWeightFilter = withWeightFilter;
            this.withCorpusName = withCorpusName;
        }

        @Override
        public Object resolve(Instruction instruction) throws ErrorMessageException {
            InstructionResolver resolver = provider.getInstructionResolver(FicheMetaFormatter.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 "corpus":
                    return CORPUS_PART;
                case "formsyntax":
                    return new FormSyntaxPart(withWeightFilter, withCorpusName);
                case "id":
                case "idcorpus":
                    return ID_PART;
                case "json": {
                    JsonParameters jsonParameters = JsonParameters.fromInstruction(instruction);
                    if (jsonParameters == null) {
                        jsonParameters = DEFAULT_JSONPARAMETERS;
                    }
                    return new JsonPart(jsonParameters);
                }
                case "lang":
                    return LANG_PART;
                case "weight":
                case "poids":
                    return WEIGHT_PART;
                case "title":
                case "titre":
                    return TITLE_PART;
                default:
                    return null;
            }
        }

    }


    private static class JsonPart implements FicheMetaFormatter {

        private final JsonParameters jsonParameters;

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

        @Override
        public String formatFicheMeta(FicheMeta ficheMeta, int weight, FormatSource formatSource) {
            Cell[] cellArray = FormatterParserUtils.resolve(ficheMeta, jsonParameters, formatSource);
            StringBuilder buf = new StringBuilder();
            JSONWriter jw = new JSONWriter(buf);
            try {
                jw.object();
                FicheMetaJson.properties(jw, ficheMeta, jsonParameters, cellArray);
                jw.endObject();
            } catch (IOException ioe) {
                throw new ShouldNotOccurException(ioe);
            }
            return buf.toString();
        }

    }


    private static class FormSyntaxPart implements FicheMetaFormatter {

        private final boolean withWeightFilter;
        private final boolean withCorpusName;

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

        @Override
        public String formatFicheMeta(FicheMeta ficheMeta, int weight, FormatSource formatSource) {
            StringBuilder buf = new StringBuilder();
            if (withCorpusName) {
                buf.append(ficheMeta.getSubsetName());
                buf.append('/');
            }
            buf.append(String.valueOf(ficheMeta.getId()));
            if ((!withWeightFilter) && (weight > 1)) {
                buf.append(" <");
                buf.append(weight);
                buf.append(">");
            }
            return buf.toString();
        }

    }


}
