/* UtilLib - Copyright (c) 2012-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.mapeadores.util.request.xml;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
import net.mapeadores.util.attr.AttributeUtils;
import net.mapeadores.util.request.RequestConfBuilder;
import net.mapeadores.util.xml.DOMUtils;
import net.mapeadores.util.xml.XMLUtils;
import org.w3c.dom.Element;


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

    private final RequestConfBuilder requestConfBuilder;

    public RequestConfDOMReader(RequestConfBuilder requestConfBuilder) {
        this.requestConfBuilder = requestConfBuilder;
    }

    public void readConf(Element element) {
        DOMUtils.readChildren(element, new ConfConsumer());
    }


    private class ConfConsumer implements Consumer<Element> {

        private ConfConsumer() {

        }

        @Override
        public void accept(Element element) {
            String tagName = element.getTagName();
            if (tagName.equals("param")) {
                String name = element.getAttribute("name");
                if (name.length() > 0) {
                    String value = element.getAttribute("value");
                    if (value.length() > 0) {
                        requestConfBuilder.addParameter(name, Collections.singleton(value));
                    } else {
                        ParameterValueConsumer parameterValueConsumer = new ParameterValueConsumer();
                        DOMUtils.readChildren(element, parameterValueConsumer);
                        if (parameterValueConsumer.isNotEmpty()) {
                            requestConfBuilder.addParameter(name, parameterValueConsumer.getList());
                        }
                    }
                }
            } else if (tagName.equals("attr")) {
                AttributeUtils.readAttrElement(requestConfBuilder.getAttributesBuilder(), element);
            }
        }

    }


    private class ParameterValueConsumer implements Consumer<Element> {

        private final List<String> values = new ArrayList<String>();

        public ParameterValueConsumer() {
        }

        @Override
        public void accept(Element element) {
            String tagName = element.getTagName();
            if (tagName.equals("val")) {
                String val = XMLUtils.getData(element);
                if (val.length() > 0) {
                    values.add(val);
                }
            }
        }

        private boolean isNotEmpty() {
            return (!values.isEmpty());
        }

        private List<String> getList() {
            return values;
        }

    }

}
