/* FichothequeLib_Tools - Copyright (c) 2013-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.dom;

import java.text.ParseException;
import java.util.function.Consumer;
import net.fichotheque.namespaces.ExtractionSpace;
import net.fichotheque.thesaurus.Motcle;
import net.fichotheque.thesaurus.ThesaurusEditor;
import net.mapeadores.util.attr.AttributeUtils;
import net.mapeadores.util.attr.AttributesBuilder;
import net.mapeadores.util.logging.MessageHandler;
import net.mapeadores.util.text.Label;
import net.mapeadores.util.text.LabelUtils;
import net.mapeadores.util.xml.DOMUtils;
import net.mapeadores.util.xml.DomMessages;
import org.w3c.dom.Element;


/**
 *
 * @author Vincent Calame
 */
public class MotcleDOMReader {

    private final MessageHandler messageHandler;
    private final ThesaurusEditor thesaurusEditor;
    private final RootConsumer rootConsumer = new RootConsumer();

    public MotcleDOMReader(ThesaurusEditor thesaurusEditor, MessageHandler messageHandler) {
        this.thesaurusEditor = thesaurusEditor;
        this.messageHandler = messageHandler;
    }

    public void fillMotcle(Motcle motcle, Element element) {
        AttributesBuilder attributesBuilder = new AttributesBuilder();
        rootConsumer.setMotcle(motcle, attributesBuilder);
        DOMUtils.readChildren(element, rootConsumer);
        thesaurusEditor.getFichothequeEditor().putAttributes(motcle, attributesBuilder.toAttributes());
    }


    private class RootConsumer implements Consumer<Element> {

        private Motcle motcle;
        private AttributesBuilder attributesBuilder;

        private RootConsumer() {
        }

        private void setMotcle(Motcle motcle, AttributesBuilder attributesBuilder) {
            this.motcle = motcle;
            this.attributesBuilder = attributesBuilder;
        }

        @Override
        public void accept(Element element) {
            String tagName = element.getTagName();
            if ((tagName.equals("label")) || (tagName.equals("lib"))) {
                try {
                    Label label = LabelUtils.readLabel(element);
                    if (label != null) {
                        thesaurusEditor.putLabel(motcle, label);
                    }
                } catch (ParseException e) {
                    DomMessages.wrongLangAttribute(messageHandler, "lib", element.getAttribute("xml:lang"));
                }
            } else if (tagName.equals("attr")) {
                AttributeUtils.readAttrElement(attributesBuilder, element, messageHandler, tagName, ExtractionSpace.EXTRACTION_ALIAS);
            } else {
                DomMessages.unknownTagWarning(messageHandler, tagName);
            }
        }

    }

}
