/* FichothequeLib_Tools - Copyright (c) 2013-2025 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.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import net.fichotheque.SubsetItem;
import net.fichotheque.junction.Tie;
import net.fichotheque.utils.JunctionUtils;
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;
import net.fichotheque.junction.JunctionChange;
import net.fichotheque.junction.Junction;
import net.fichotheque.junction.JunctionEditor;


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

    private final JunctionEditor junctionEditor;
    private final MessageHandler messageHandler;
    private final RootConsumer rootConsumer = new RootConsumer();

    public JunctionDOMReader(JunctionEditor junctionEditor, MessageHandler messageHandler) {
        this.junctionEditor = junctionEditor;
        this.messageHandler = messageHandler;
    }

    public void readJunction(Element element, SubsetItem subsetItem1, SubsetItem subsetItem2) {
        rootConsumer.clear();
        DOMUtils.readChildren(element, rootConsumer);
        rootConsumer.flush(subsetItem1, subsetItem2);
    }


    private class RootConsumer implements Consumer<Element> {

        private final Map<String, Tie> tieMap = new LinkedHashMap<String, Tie>();
        private AttributesBuilder attributesBuilder;

        private RootConsumer() {
        }

        private void clear() {
            tieMap.clear();
            attributesBuilder = null;
        }

        private void flush(SubsetItem subsetItem1, SubsetItem subsetItem2) {
            List<Tie> tieList = JunctionUtils.wrap(tieMap.values().toArray(new Tie[tieMap.size()]));
            JunctionChange junctionChange = new InternalJunctionChange(tieList);
            Junction junction = junctionEditor.updateJunction(subsetItem1, subsetItem2, junctionChange);
            if ((junction != null) && (attributesBuilder != null)) {
                junctionEditor.getFichothequeEditor().putAttributes(junction, attributesBuilder.toAttributes());
            }
        }

        @Override
        public void accept(Element element) {
            String tagName = element.getTagName();
            switch (element.getTagName()) {
                case "tie":
                case "lien":
                    String mode = element.getAttribute("mode");
                    int weight = getWeight(element);
                    int position1 = getPosition(element, "position1");
                    int position2 = getPosition(element, "position2");
                    Tie tie = JunctionUtils.toTie(mode, weight, position1, position2);
                    tieMap.put(mode, tie);
                    break;
                case "attr":
                    if (attributesBuilder == null) {
                        attributesBuilder = new AttributesBuilder();
                    }
                    AttributeUtils.readAttrElement(attributesBuilder, element, messageHandler, tagName);
                    break;
                default:
                    DomMessages.unknownTagWarning(messageHandler, tagName);
            }
        }

        private int getWeight(Element element) {
            int weight = 1;
            String weightString = element.getAttribute("weight");
            if (weightString.isEmpty()) {
                weightString = element.getAttribute("poids");
            }
            if (weightString.length() > 0) {
                try {
                    weight = Integer.parseInt(weightString);
                    if (weight < 1) {
                        weight = 1;
                    }
                } catch (NumberFormatException nfe) {
                }
            }
            return weight;
        }

        private int getPosition(Element element, String attributeName) {
            int position = 0;
            String posString = element.getAttribute(attributeName);
            if (posString.length() > 0) {
                try {
                    position = Integer.parseInt(posString);
                    if (position < 0) {
                        position = 0;
                    }
                } catch (NumberFormatException nfe) {
                }
            }
            return position;
        }

    }


    private static class InternalJunctionChange implements JunctionChange {

        private final List<Tie> changedTieList;

        private InternalJunctionChange(List<Tie> changedTieList) {
            this.changedTieList = changedTieList;
        }

        @Override
        public List<String> getRemovedModeList() {
            return JunctionUtils.EMPTY_REMOVEDMODELIST;
        }

        @Override
        public List<Tie> getChangedTieList() {
            return changedTieList;
        }

    }

}
