001/*
002 * PlotSquared, a land and world management plugin for Minecraft.
003 * Copyright (C) IntellectualSites <https://intellectualsites.com>
004 * Copyright (C) IntellectualSites team and contributors
005 *
006 * This program is free software: you can redistribute it and/or modify
007 * it under the terms of the GNU General Public License as published by
008 * the Free Software Foundation, either version 3 of the License, or
009 * (at your option) any later version.
010 *
011 * This program is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
014 * GNU General Public License for more details.
015 *
016 * You should have received a copy of the GNU General Public License
017 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
018 */
019package com.plotsquared.core.plot.flag.types;
020
021import com.plotsquared.core.configuration.caption.Caption;
022import com.plotsquared.core.configuration.caption.TranslatableCaption;
023import com.plotsquared.core.plot.flag.FlagParseException;
024import com.plotsquared.core.plot.flag.PlotFlag;
025import org.checkerframework.checker.nullness.qual.NonNull;
026
027public abstract class NumberFlag<N extends Number & Comparable<N>, F extends PlotFlag<N, F>>
028        extends PlotFlag<N, F> {
029
030    protected final N minimum;
031    protected final N maximum;
032
033    protected NumberFlag(
034            @NonNull N value, N minimum, N maximum, @NonNull Caption flagCategory,
035            @NonNull Caption flagDescription
036    ) {
037        super(value, flagCategory, flagDescription);
038        if (maximum.compareTo(minimum) < 0) {
039            throw new IllegalArgumentException(
040                    "Maximum may not be less than minimum:" + maximum + " < " + minimum);
041        }
042        this.minimum = minimum;
043        this.maximum = maximum;
044    }
045
046    @Override
047    public F parse(@NonNull String input) throws FlagParseException {
048        final N parsed = parseNumber(input);
049        if (parsed.compareTo(minimum) < 0 || parsed.compareTo(maximum) > 0) {
050            throw new FlagParseException(this, input, TranslatableCaption.of("flags.flag_error_integer"));
051        }
052        return flagOf(parsed);
053
054    }
055
056    /**
057     * Parse the raw string input to the number type.
058     *
059     * @param input the string to parse the number from.
060     * @return the parsed number.
061     * @throws FlagParseException if the number couldn't be parsed.
062     */
063    @NonNull
064    protected abstract N parseNumber(String input) throws FlagParseException;
065
066}