001package jmri;
002
003/**
004 * Defines a permission based on a boolean.
005 *
006 * @author Daniel Bergqvist (C) 2024
007 */
008public interface BooleanPermission extends Permission {
009
010    public static class BooleanValue implements PermissionValue {
011
012        public static final BooleanValue TRUE = new BooleanValue(true);
013        public static final BooleanValue FALSE = new BooleanValue(false);
014
015        private final boolean _value;
016
017        public boolean get() {
018            return _value;
019        }
020
021        public static BooleanValue get(boolean value) {
022            return value ? TRUE : FALSE;
023        }
024
025        private BooleanValue(boolean value) {
026            this._value = value;
027        }
028
029        @Override
030        public boolean isDefault() {
031            return false;
032        }
033
034        @Override
035        public String toString() {
036            return Boolean.toString(_value);
037        }
038    }
039
040    @Override
041    default String getValue(PermissionValue value) {
042        if (!(value instanceof BooleanValue)) {
043            throw new IllegalArgumentException("value is not a BooleanValue");
044        }
045        return ((BooleanValue)value).get() ? "yes" : "no";
046    }
047
048    @Override
049    default PermissionValue valueOf(String value) {
050        return BooleanValue.get("yes".equals(value));
051    }
052
053    /**
054     * Get the default permission for a role.
055     * @return the default
056     */
057    @Override
058    default BooleanValue getDefaultPermission() {
059        return BooleanValue.FALSE;
060    }
061
062    /**
063     * Get the default permission for a role.
064     * @param role the role
065     * @return the default
066     */
067    @Override
068    BooleanValue getDefaultPermission(Role role);
069
070    @Override
071    default int compare(PermissionValue o1, PermissionValue o2) {
072        if (o1 instanceof BooleanValue && o2 instanceof BooleanValue) {
073            boolean b1 = ((BooleanValue) o1).get();
074            boolean b2 = ((BooleanValue) o2).get();
075            return Boolean.compare(b1, b2);
076        } else {
077            throw new IllegalArgumentException("Cannot compare o1 and o2 since one or both is not a BooleanValue");
078        }
079    }
080
081}