/* BdfServer - Copyright (c) 2016-2024 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.exportation.transformation.dom;

import java.text.ParseException;
import java.util.function.Consumer;
import net.fichotheque.tools.exportation.transformation.TemplateDefBuilder;
import net.mapeadores.util.attr.AttributeUtils;
import net.mapeadores.util.logging.MessageHandler;
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 TemplateDefDOMReader {

    private final TemplateDefBuilder templateDefBuilder;
    private final MessageHandler messageHandler;

    public TemplateDefDOMReader(TemplateDefBuilder templateDefBuilder, MessageHandler messageHandler) {
        this.templateDefBuilder = templateDefBuilder;
        this.messageHandler = messageHandler;
    }

    public TemplateDefDOMReader read(Element element) {
        DOMUtils.readChildren(element, new RootConsumer());
        return this;
    }

    public static TemplateDefDOMReader init(TemplateDefBuilder templateDefBuilder, MessageHandler messageHandler) {
        return new TemplateDefDOMReader(templateDefBuilder, messageHandler);
    }


    private class RootConsumer implements Consumer<Element> {

        private RootConsumer() {
        }

        @Override
        public void accept(Element element) {
            String tagName = element.getTagName();
            switch (tagName) {
                case "label": {
                    try {
                        LabelUtils.readLabel(element, templateDefBuilder);
                    } catch (ParseException ile) {
                        DomMessages.wrongLangAttribute(messageHandler, tagName, element.getAttribute("xml:lang"));
                    }
                    break;
                }
                case "attr":
                    AttributeUtils.readAttrElement(templateDefBuilder.getAttributesBuilder(), element);
                    break;
                default:
                    DomMessages.unknownTagWarning(messageHandler, tagName);
            }
        }

    }

}
