/* BdfServer - Copyright (c) 2008-2023 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.xml.roles;

import fr.exemole.bdfserver.api.roles.FichePermission;
import fr.exemole.bdfserver.api.roles.Permission;
import fr.exemole.bdfserver.api.roles.RoleDef;
import fr.exemole.bdfserver.tools.roles.RoleUtils;
import java.io.IOException;
import net.fichotheque.SubsetKey;
import net.fichotheque.eligibility.SubsetEligibility;
import net.fichotheque.utils.EligibilityUtils;
import net.mapeadores.util.annotation.Nullable;
import net.mapeadores.util.attr.AttributeUtils;
import net.mapeadores.util.text.LabelUtils;
import net.mapeadores.util.xml.XMLPart;
import net.mapeadores.util.xml.XMLWriter;


/**
 *
 * @author Vincent Calame
 */
public class RoleDefXMLPart extends XMLPart {

    public RoleDefXMLPart(XMLWriter xmlWriter) {
        super(xmlWriter);
    }

    public void addRoleDef(RoleDef roleDef) throws IOException {
        addRoleDef(roleDef, null);
    }

    public void addRoleDef(RoleDef roleDef, @Nullable SubsetEligibility subsetEligibility) throws IOException {
        if (subsetEligibility == null) {
            subsetEligibility = EligibilityUtils.ALL_SUBSET_ELIGIBILITY;
        }
        openTag("role");
        LabelUtils.addLabels(this, roleDef.getTitleLabels());
        for (RoleDef.SubsetEntry entry : roleDef.getSubsetEntryList()) {
            SubsetKey subsetKey = entry.getSubsetKey();
            if (subsetEligibility.accept(subsetKey)) {
                appendSubsetPermission(subsetKey, entry.getPermission());
            }
        }
        AttributeUtils.addAttributes(this, roleDef.getAttributes());
        closeTag("role");
    }

    private void appendSubsetPermission(SubsetKey subsetKey, Permission permission) throws IOException {
        short level = permission.getLevel();
        startOpenTag("subset-permission");
        addAttribute("subset", subsetKey.getKeyString());
        addAttribute("level", RoleUtils.levelToString(level));
        if (level != Permission.CUSTOM_LEVEL) {
            closeEmptyTag();
        } else {
            endOpenTag();
            if (subsetKey.isCorpusSubset()) {
                FichePermission fichePermission = (FichePermission) permission.getCustomPermission();
                if (fichePermission.create()) {
                    addEmptyElement("create");
                }
                startOpenTag("read");
                addAttribute("type", RoleUtils.fichePermissionTypeToString(fichePermission.read()));
                closeEmptyTag();
                startOpenTag("write");
                addAttribute("type", RoleUtils.fichePermissionTypeToString(fichePermission.write()));
                closeEmptyTag();
            }
            closeTag("subset-permission");
        }
    }

}
