/* 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.util.function.Consumer;
import net.fichotheque.album.AlbumEditor;
import net.fichotheque.album.Illustration;
import net.mapeadores.util.attr.AttributeUtils;
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 org.w3c.dom.Element;


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

    private final MessageHandler messageHandler;
    private final AlbumEditor albumEditor;
    private final RootConsumer rootConsumer = new RootConsumer();

    public IllustrationDOMReader(AlbumEditor albumEditor, MessageHandler messageHandler) {
        this.albumEditor = albumEditor;
        this.messageHandler = messageHandler;
    }

    public void fillIllustration(Illustration illustration, Element element) {
        AttributesBuilder attributesBuilder = new AttributesBuilder();
        rootConsumer.setIllustration(illustration, attributesBuilder);
        DOMUtils.readChildren(element, rootConsumer);
        albumEditor.getFichothequeEditor().putAttributes(illustration, attributesBuilder.toAttributes());
    }


    private class RootConsumer implements Consumer<Element> {

        private Illustration illustration;
        private AttributesBuilder attributesBuilder;

        private RootConsumer() {
        }

        private void setIllustration(Illustration illustration, AttributesBuilder attributesBuilder) {
            this.illustration = illustration;
            this.attributesBuilder = attributesBuilder;

        }

        @Override
        public void accept(Element element) {
            String tagName = element.getTagName();
            if (tagName.equals("attr")) {
                AttributeUtils.readAttrElement(attributesBuilder, element, messageHandler, tagName);
            } else {
                DomMessages.unknownTagWarning(messageHandler, tagName);
            }
        }

    }

}
