/* FichothequeLib_Tools - Copyright (c) 2015-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 net.fichotheque.tools.permission;

import java.util.function.Predicate;
import net.fichotheque.Subset;
import net.fichotheque.SubsetItem;
import net.fichotheque.SubsetKey;
import net.fichotheque.eligibility.SubsetEligibility;
import net.fichotheque.permission.PermissionSummary;


/**
 *
 * @author Vincent Calame
 */
public class PermissionSubsetEligibility implements SubsetEligibility {

    private final PermissionSummary permissionSummary;
    private final boolean read;
    private final Predicate<SubsetItem> permissionPredicate;

    private PermissionSubsetEligibility(PermissionSummary permissionSummary, boolean read) {
        this.permissionSummary = permissionSummary;
        this.read = read;
        if (read) {
            this.permissionPredicate = PermissionPredicate.read(permissionSummary);
        } else {
            this.permissionPredicate = PermissionPredicate.write(permissionSummary);
        }

    }

    @Override
    public boolean accept(SubsetKey subsetKey) {
        int level;
        if (read) {
            level = permissionSummary.getReadLevel(subsetKey);
        } else {
            level = permissionSummary.getWriteLevel(subsetKey);
        }
        return (level != PermissionSummary.SUMMARYLEVEL_0_NONE);
    }

    @Override
    public Predicate<SubsetItem> getPredicate(Subset subset) {
        return permissionPredicate;
    }

    public static PermissionSubsetEligibility read(PermissionSummary permissionSummary) {
        return new PermissionSubsetEligibility(permissionSummary, true);
    }

    public static PermissionSubsetEligibility write(PermissionSummary permissionSummary) {
        return new PermissionSubsetEligibility(permissionSummary, false);
    }

}
