/* BdfServer_Multi - Copyright (c) 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 fr.exemole.bdfserver.multi.tools.dom;

import fr.exemole.bdfserver.multi.api.MultiMetadataEditor;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.function.Consumer;
import net.fichotheque.tools.dom.AbstractMetadataDOMReader;
import net.mapeadores.util.attr.AttributesBuilder;
import net.mapeadores.util.localisation.Lang;
import net.mapeadores.util.localisation.LangsUtils;
import net.mapeadores.util.logging.MessageHandler;
import net.mapeadores.util.text.StringUtils;
import net.mapeadores.util.xml.DOMUtils;
import net.mapeadores.util.xml.DomMessages;
import org.w3c.dom.Element;


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

    private final MultiMetadataEditor multiMetadataEditor;


    public MultiMetadataDOMReader(MultiMetadataEditor multiMetadataEditor, MessageHandler messageHandler) {
        super(multiMetadataEditor, messageHandler);
        this.multiMetadataEditor = multiMetadataEditor;
    }

    public void read(Element element) {
        AttributesBuilder attributesBuilder = new AttributesBuilder();
        RootConsumer rootConsumer = new RootConsumer(attributesBuilder, "/" + element.getTagName());
        DOMUtils.readChildren(element, rootConsumer);
        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")) {
                String authority = DOMUtils.readSimpleElement(element);
                if (StringUtils.isAuthority(authority)) {
                    multiMetadataEditor.setAuthority(authority);
                } else {
                    DomMessages.wrongElementValue(messageHandler, xpath, authority);
                }
            } else if (tagName.equals("working-langs")) {
                Set<Lang> langSet = new LinkedHashSet();
                LangsUtils.readLangElements(langSet, element, messageHandler, xpath);
                if (!langSet.isEmpty()) {
                    multiMetadataEditor.setWorkingLangs(LangsUtils.fromCollection(langSet));
                }
            }
        }

    }


}
