/* 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.SubsetItem;
import net.fichotheque.corpus.FicheMeta;
import net.fichotheque.permission.PermissionSummary;
import net.mapeadores.util.exceptions.SwitchException;


/**
 *
 * @author Vincent Calame
 */
public class PermissionPredicate implements Predicate<SubsetItem> {

    private final PermissionSummary permissionSummary;
    private final boolean read;


    private PermissionPredicate(PermissionSummary permissionSummary, boolean read) {
        this.permissionSummary = permissionSummary;
        this.read = read;
    }


    @Override
    public boolean test(SubsetItem subsetItem) {
        if (subsetItem instanceof FicheMeta) {
            if (read) {
                return permissionSummary.canRead((FicheMeta) subsetItem);
            } else {
                return permissionSummary.canWrite((FicheMeta) subsetItem);
            }
        } else {
            int level;
            if (read) {
                level = permissionSummary.getReadLevel(subsetItem.getSubsetKey());
            } else {
                level = permissionSummary.getWriteLevel(subsetItem.getSubsetKey());
            }
            switch (level) {
                case PermissionSummary.SUMMARYLEVEL_0_NONE:
                    return false;
                case PermissionSummary.SUMMARYLEVEL_1_FICHE_OWN:
                case PermissionSummary.SUMMARYLEVEL_2_FICHE_SPHERE:
                    throw new IllegalStateException("Level only available for corpus: " + level);
                case PermissionSummary.SUMMARYLEVEL_3_CROISEMENT_TEST:
                    return PermissionUtils.croisementTest(subsetItem, permissionSummary, read);
                case PermissionSummary.SUMMARYLEVEL_4_ALL:
                case PermissionSummary.SUMMARYLEVEL_5_ADMIN:
                    return true;
                default:
                    throw new SwitchException("Unknown level: " + level);
            }
        }
    }

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

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

}
