001/*
002 * PermissionsEx
003 * Copyright (C) zml and PermissionsEx contributors
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *    http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package ca.stellardrift.permissionsex.context;
018
019import ca.stellardrift.permissionsex.subject.CalculatedSubject;
020import org.checkerframework.checker.nullness.qual.Nullable;
021import org.pcollections.HashTreePSet;
022
023import java.util.Arrays;
024import java.util.Set;
025import java.util.function.Consumer;
026
027public abstract class EnumContextDefinition<T extends Enum<T>> extends ContextDefinition<T> {
028    private final Class<T> enumClass;
029    private final Set<T> values;
030
031    protected EnumContextDefinition(final String name, final Class<T> enumClass) {
032        super(name);
033        this.enumClass = enumClass;
034        assert this.enumClass.isEnum(); // true because of type bound
035
036        this.values = HashTreePSet.from(Arrays.asList(this.enumClass.getEnumConstants()));
037    }
038
039    @Override
040    public final String serialize(final T canonicalValue) {
041        return canonicalValue.name();
042    }
043
044    @Override
045    public final @Nullable T deserialize(final String userValue) {
046        try {
047            return Enum.valueOf(enumClass, userValue.toUpperCase());
048        } catch (final IllegalArgumentException ex) {
049            return null;
050        }
051    }
052
053    @Override
054    public boolean matches(final T ownVal, final T testVal) {
055        return ownVal == testVal;
056    }
057
058    @Override
059    public void accumulateCurrentValues(final CalculatedSubject subject, final Consumer<T> consumer) {
060    }
061
062    @Override
063    public Set<T> suggestValues(final CalculatedSubject subject) {
064        return this.values;
065    }
066}