/* BdfServer - Copyright (c) 2023 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 fr.exemole.bdfserver.tools.overview;

import fr.exemole.bdfserver.api.EditSession;
import fr.exemole.bdfserver.api.ui.UiComponents;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import net.fichotheque.corpus.metadata.CorpusField;
import net.fichotheque.corpus.metadata.CorpusMetadata;
import net.fichotheque.corpus.metadata.CorpusMetadataEditor;
import net.fichotheque.corpus.metadata.FieldGeneration;
import net.fichotheque.corpus.metadata.FieldKey;
import net.fichotheque.tools.corpus.FieldGenerationParser;
import net.fichotheque.utils.FichothequeUtils;
import net.mapeadores.util.attr.AttributeChangeBuilder;
import net.mapeadores.util.localisation.Lang;
import net.mapeadores.util.logging.LineMessageException;
import net.mapeadores.util.logging.LineLogsBuilder;
import net.mapeadores.util.text.LabelChangeBuilder;
import net.mapeadores.util.text.StringUtils;


/**
 *
 * @author Vincent Calame
 */
class MetadataBlock extends OverviewBlock {

    private final CorpusMetadata corpusMetadata;
    private final AttributeChangeBuilder attributeChangeBuilder = new AttributeChangeBuilder();
    private final Map<String, LabelChangeBuilder> phraseChangeMap = new HashMap<String, LabelChangeBuilder>();
    private final LabelChangeBuilder titleLabelChangeBuilder = new LabelChangeBuilder();
    private FieldKey geolocalisationFieldKey;
    private boolean removeGeolocalisation;
    private FieldGeneration fieldGeneration;
    private String[] order;

    MetadataBlock(int lineNumber, CorpusMetadata corpusMetadata) {
        super(lineNumber, "metadata");
        this.corpusMetadata = corpusMetadata;
    }

    @Override
    public boolean addText(String name, Lang lang, String text) {
        LabelChangeBuilder labelChangeBuilder = getLabelChangeBuilder(name);
        if (labelChangeBuilder == null) {
            return false;
        }
        labelChangeBuilder.putLabel(lang, text);
        return true;
    }

    private LabelChangeBuilder getLabelChangeBuilder(String name) {
        if (name.equals("title")) {
            return titleLabelChangeBuilder;
        }
        if (name.startsWith("phrase_")) {
            String phraseName = name.substring("phrase_".length());
            LabelChangeBuilder labelChangeBuilder = phraseChangeMap.get(phraseName);
            if (labelChangeBuilder != null) {
                return labelChangeBuilder;
            } else {
                if (FichothequeUtils.isValidPhraseName(name)) {
                    labelChangeBuilder = new LabelChangeBuilder();
                    phraseChangeMap.put(phraseName, labelChangeBuilder);
                    return labelChangeBuilder;
                } else {
                    return null;
                }
            }
        }
        return null;
    }

    @Override
    public void put(int lineNumber, String key, String value) throws LineMessageException {
        switch (key) {
            case "order": {
                order = StringUtils.getTechnicalTokens(value, true);
                break;
            }
            case "geolocalisation": {
                if (value.isEmpty()) {
                    removeGeolocalisation = true;
                } else {
                    try {
                        FieldKey fieldKey = FieldKey.parse(value);
                        if (fieldKey.isProp()) {
                            geolocalisationFieldKey = fieldKey;
                        } else {
                            throw new LineMessageException(lineNumber, OverviewEngine.SEVERE_FICHOTHEQUE, "_ error.wrong.parametervalue", key, value);
                        }
                    } catch (ParseException pe) {
                        throw new LineMessageException(lineNumber, OverviewEngine.SEVERE_FICHOTHEQUE, "_ error.wrong.parametervalue", key, value);
                    }
                }
                break;
            }
            case "fieldgeneration": {
                LineLogsBuilder lingeLogsBuilder = new LineLogsBuilder();
                fieldGeneration = FieldGenerationParser.parse(value, lingeLogsBuilder);
                if (lingeLogsBuilder.hasMessage()) {
                    throw new LineMessageException(lineNumber, OverviewEngine.SEVERE_FICHOTHEQUE, "_ error.wrong.parametervalue", key, value);
                }
                break;
            }
            default:
                throw new LineMessageException(lineNumber, OverviewEngine.SEVERE_FICHOTHEQUE, "_ error.unknown.conf.key", key);
        }
    }

    @Override
    public void put(int lineNumber, String key, String name, String value) throws LineMessageException {
        throw new LineMessageException(lineNumber, OverviewEngine.SEVERE_FICHOTHEQUE, "_ error.unknown.conf.key", key);

    }

    @Override
    public AttributeChangeBuilder getAttributeChangeBuilder() {
        return attributeChangeBuilder;
    }

    @Override
    public void firstPass(EditSession editSession, UiComponents uiComponents) {
        CorpusMetadataEditor corpusMetadataEditor = editSession.getFichothequeEditor().getCorpusEditor(corpusMetadata.getCorpus()).getCorpusMetadataEditor();
        corpusMetadataEditor.changeLabels(null, titleLabelChangeBuilder.toLabelChange());
        for (Map.Entry<String, LabelChangeBuilder> entry : phraseChangeMap.entrySet()) {
            corpusMetadataEditor.changeLabels(entry.getKey(), entry.getValue().toLabelChange());
        }
        corpusMetadataEditor.changeAttributes(attributeChangeBuilder.toAttributeChange());
    }

    @Override
    public void secondPass(EditSession editSession, UiComponents uiComponents) {
        CorpusMetadataEditor corpusMetadataEditor = editSession.getFichothequeEditor().getCorpusEditor(corpusMetadata.getCorpus()).getCorpusMetadataEditor();
        if (geolocalisationFieldKey != null) {
            CorpusField corpusField = corpusMetadata.getCorpusField(geolocalisationFieldKey);
            if (corpusField != null) {
                try {
                    corpusMetadataEditor.setGeolocalisationField(corpusField);
                } catch (IllegalArgumentException iae) {

                }
            }
        } else if (removeGeolocalisation) {
            corpusMetadataEditor.setGeolocalisationField(null);
        }
        if (fieldGeneration != null) {
            corpusMetadataEditor.setFieldGeneration(fieldGeneration);
        }
        if (order != null) {
            editSession.getBdfServerEditor().setPositionArray(uiComponents, order);
        }
    }

}
