/* FichothequeLib_Xml - Copyright (c) 2008-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.util.function.Consumer;
import net.fichotheque.metadata.FichothequeMetadataEditor;
import net.mapeadores.util.attr.AttributesBuilder;
import net.mapeadores.util.logging.MessageHandler;
import net.mapeadores.util.xml.DOMUtils;
import net.mapeadores.util.xml.DomMessages;
import net.mapeadores.util.xml.XMLUtils;
import org.w3c.dom.Element;


/**
 *
 * @author Vincent Calame
 */
public class FichothequeMetadataDOMReader extends AbstractMetadataDOMReader {

    private final FichothequeMetadataEditor fichothequeMetadataEditor;

    public FichothequeMetadataDOMReader(FichothequeMetadataEditor fichothequeMetadataEditor, MessageHandler messageHandler) {
        super(fichothequeMetadataEditor, messageHandler, "short");
        this.fichothequeMetadataEditor = fichothequeMetadataEditor;
    }

    public void fillMetadata(Element element) {
        AttributesBuilder attributesBuilder = new AttributesBuilder();
        DOMUtils.readChildren(element, new RootConsumer(attributesBuilder, "/" + element.getTagName()));
        flush(attributesBuilder);
    }


    private class RootConsumer implements Consumer<Element> {

        private final AttributesBuilder attributesBuilder;
        private final String parentXpath;

        private RootConsumer(AttributesBuilder attributesBuilder, String parentXpath) {
            this.attributesBuilder = attributesBuilder;
            this.parentXpath = parentXpath;
        }

        @Override
        public void accept(Element element) {
            if (readCommonElement(element, attributesBuilder, parentXpath)) {
                return;
            }
            String tagname = element.getTagName();
            String xpath = parentXpath + "/" + tagname;
            if ((tagname.equals("authority")) || (tagname.equals("authority-uuid"))) {
                String authority = XMLUtils.getData(element);
                try {
                    fichothequeMetadataEditor.setAuthority(authority);
                } catch (IllegalArgumentException pe) {
                    DomMessages.wrongElementValue(messageHandler, xpath, authority);
                }
            } else if ((tagname.equals("base-name")) || (tagname.equals("basedefiches-name"))) {
                String name = XMLUtils.getData(element);
                try {
                    fichothequeMetadataEditor.setBaseName(name);
                } catch (IllegalArgumentException pe) {
                    DomMessages.wrongElementValue(messageHandler, xpath, name);
                }
            } else {
                DomMessages.unknownTagWarning(messageHandler, xpath);
            }

        }

    }

}
