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

import fr.exemole.bdfserver.api.roles.FichePermission;
import fr.exemole.bdfserver.api.roles.Permission;
import fr.exemole.bdfserver.tools.roles.RoleDefBuilder;
import fr.exemole.bdfserver.tools.roles.RoleUtils;
import java.text.ParseException;
import java.util.function.Consumer;
import net.fichotheque.SubsetKey;
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;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


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

    private final RoleDefBuilder roleDefBuilder;
    private final MessageHandler messageHandler;

    public RoleDefDOMReader(RoleDefBuilder roleDefBuilder, MessageHandler messageHandler) {
        this.messageHandler = messageHandler;
        this.roleDefBuilder = roleDefBuilder;
    }

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

    public static RoleDefDOMReader init(RoleDefBuilder roleDefBuilder, MessageHandler messageHandler) {
        return new RoleDefDOMReader(roleDefBuilder, messageHandler);
    }


    private class RootConsumer implements Consumer<Element> {

        private RootConsumer() {
        }

        @Override
        public void accept(Element element) {
            String tagName = element.getTagName();
            switch (tagName) {
                case "lib-list":
                    readOldLibList(element);
                    break;
                case "corpus-permission":
                    readOldCorpusPermission(element);
                    break;
                case "subset-permission":
                    readSubsetPermission(element);
                    break;
                case "label":
                case "lib": {
                    try {
                        LabelUtils.readLabel(element, roleDefBuilder);
                    } catch (ParseException ile) {
                        DomMessages.wrongLangAttribute(messageHandler, tagName, element.getAttribute("xml:lang"));
                    }
                    break;
                }
                case "attr":
                    AttributeUtils.readAttrElement(roleDefBuilder.getAttributesBuilder(), element);
                    break;
                default:
                    DomMessages.unknownTagWarning(messageHandler, tagName);
            }
        }

    }

    private void readOldLibList(Element element_xml) {
        NodeList liste = element_xml.getChildNodes();
        for (int i = 0; i < liste.getLength(); i++) {
            if (liste.item(i).getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) liste.item(i);
                String tagName = element.getTagName();
                if (tagName.equals("lib")) {
                    try {
                        LabelUtils.readLabel(element, roleDefBuilder);
                    } catch (ParseException ile) {
                        DomMessages.wrongLangAttribute(messageHandler, tagName, element.getAttribute("xml:lang"));
                    }
                } else {
                    DomMessages.unknownTagWarning(messageHandler, tagName);
                }
            }
        }
    }

    private void readSubsetPermission(Element element_xml) {
        SubsetKey subsetKey;
        try {
            subsetKey = SubsetKey.parse(element_xml.getAttribute("subset"));
        } catch (ParseException pe) {
            return;
        }
        short level = readLevel(element_xml);
        if (level < 0) {
            return;
        }
        Permission.CustomPermission customPermission = null;
        if (level == Permission.CUSTOM_LEVEL) {
            if (subsetKey.isCorpusSubset()) {
                boolean create = false;
                short read = FichePermission.NONE;
                short write = FichePermission.NONE;
                NodeList liste = element_xml.getChildNodes();
                for (int i = 0; i < liste.getLength(); i++) {
                    if (liste.item(i).getNodeType() == Node.ELEMENT_NODE) {
                        Element element = (Element) liste.item(i);
                        String tagName = element.getTagName();
                        if (tagName.equals("create")) {
                            create = true;
                        } else if (tagName.equals("read")) {
                            short type = readFichePermissionType(element);
                            if (type != 0) {
                                read = type;
                            }
                        } else if (tagName.equals("write")) {
                            short type = readFichePermissionType(element);
                            if (type != 0) {
                                write = type;
                            }
                        } else {
                            DomMessages.unknownTagWarning(messageHandler, tagName);
                        }
                    }
                }
                if (read == FichePermission.NONE) {
                    level = Permission.NONE_LEVEL;
                } else {
                    customPermission = RoleUtils.toFichePermission(create, read, write);
                    if (RoleUtils.matchStandardPermission((FichePermission) customPermission)) {
                        level = Permission.STANDARD_LEVEL;
                        customPermission = null;
                    }
                }
            } else {
                level = Permission.STANDARD_LEVEL;
            }
        }
        roleDefBuilder.putSubsetPermission(subsetKey, RoleUtils.toPermission(level, customPermission));
    }

    private void readOldCorpusPermission(Element element_xml) {
        String corpusName = element_xml.getAttribute("corpus");
        SubsetKey corpusKey;
        try {
            corpusKey = SubsetKey.parse(SubsetKey.CATEGORY_CORPUS, corpusName);
        } catch (ParseException pe) {
            return;
        }
        boolean create = false;
        short read = FichePermission.NONE;
        short write = FichePermission.NONE;
        NodeList liste = element_xml.getChildNodes();
        for (int i = 0; i < liste.getLength(); i++) {
            if (liste.item(i).getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) liste.item(i);
                String tagName = element.getTagName();
                if (tagName.equals("create-fiche")) {
                    create = true;
                } else if (tagName.equals("read-fiche")) {
                    short type = readFichePermissionType(element);
                    if (type != 0) {
                        read = type;
                    }
                } else if (tagName.equals("write-fiche")) {
                    short type = readFichePermissionType(element);
                    if (type != 0) {
                        write = type;
                    }
                } else if (tagName.equals("send-fiche")) {
                } else {
                    DomMessages.unknownTagWarning(messageHandler, tagName);
                }
            }
        }
        short level;
        FichePermission fichePermission = null;
        if (read == FichePermission.NONE) {
            level = Permission.NONE_LEVEL;
        } else {
            fichePermission = RoleUtils.toFichePermission(create, read, write);
            if (RoleUtils.matchStandardPermission(fichePermission)) {
                level = Permission.STANDARD_LEVEL;
                fichePermission = null;
            } else {
                level = Permission.CUSTOM_LEVEL;
            }
        }
        roleDefBuilder.putSubsetPermission(corpusKey, RoleUtils.toPermission(level, fichePermission));
    }

    private short readFichePermissionType(Element element_xml) {
        String typeString = element_xml.getAttribute("type");
        if (typeString.length() == 0) {
            DomMessages.emptyAttribute(messageHandler, element_xml.getTagName(), "type");
            return 0;
        }
        try {
            return RoleUtils.fichePermissionTypeToShort(typeString);
        } catch (IllegalArgumentException iae) {
            DomMessages.wrongAttributeValue(messageHandler, element_xml.getTagName(), "type", typeString);
            return 0;
        }
    }

    private short readLevel(Element element_xml) {
        String levelString = element_xml.getAttribute("level");
        if (levelString.length() == 0) {
            DomMessages.emptyAttribute(messageHandler, element_xml.getTagName(), "level");
            return -1;
        }
        try {
            return RoleUtils.levelToShort(levelString);
        } catch (IllegalArgumentException iae) {
            DomMessages.wrongAttributeValue(messageHandler, element_xml.getTagName(), "level", levelString);
            return -1;
        }
    }

}
