/* 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.ExistingNameException;
import net.fichotheque.FichothequeConstants;
import net.fichotheque.addenda.AddendaEditor;
import net.fichotheque.addenda.Document;
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 DocumentDOMReader {

    private final MessageHandler messageHandler;
    private final AddendaEditor addendaEditor;
    private final RootConsumer rootConsumer = new RootConsumer();

    public DocumentDOMReader(AddendaEditor addendaEditor, MessageHandler messageHandler) {
        this.messageHandler = messageHandler;
        this.addendaEditor = addendaEditor;
    }

    public void fillDocument(Document document, Element element) {
        String basename = element.getAttribute("basename");
        if (basename.length() > 0) {
            try {
                addendaEditor.setBasename(document, basename);
            } catch (ExistingNameException ebe) {
                messageHandler.addMessage(FichothequeConstants.SEVERE_FICHOTHEQUE, "_ error.existing.documentname", basename);
            } catch (ParseException pe) {
                DomMessages.wrongAttributeValue(messageHandler, element.getTagName(), "basename", basename);
            }
        }
        AttributesBuilder attributesBuilder = new AttributesBuilder();
        rootConsumer.setDocument(document, attributesBuilder);
        DOMUtils.readChildren(element, rootConsumer);
        addendaEditor.getFichothequeEditor().putAttributes(document, attributesBuilder.toAttributes());
    }


    private class RootConsumer implements Consumer<Element> {

        private Document document;
        private AttributesBuilder attributesBuilder;

        private RootConsumer() {
        }

        private void setDocument(Document document, AttributesBuilder attributesBuilder) {
            this.document = document;
            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);
            }
        }

    }

}
