summaryrefslogtreecommitdiff
path: root/dicore3/command/src/main/java/io/dico/dicore/command/parameter/type/NumberParameterType.java
blob: 4aac122bbf7f6057aab6dc940a4ac40e0b23ce93 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package io.dico.dicore.command.parameter.type;

import io.dico.dicore.command.CommandException;
import io.dico.dicore.command.annotation.Range;
import io.dico.dicore.command.parameter.ArgumentBuffer;
import io.dico.dicore.command.parameter.Parameter;
import org.bukkit.command.CommandSender;

/**
 * Abstraction for number parameter types which use {@link Range.Memory} as parameter info.
 *
 * @param <T> the Number subclass.
 */
public abstract class NumberParameterType<T extends Number> extends ParameterType<T, Range.Memory> {

    public NumberParameterType(Class<T> returnType) {
        super(returnType, Range.CONFIG);
    }

    protected abstract T parse(String input) throws NumberFormatException;

    protected abstract T select(Number number);

    @Override
    public T parse(Parameter<T, Range.Memory> parameter, CommandSender sender, ArgumentBuffer buffer) throws CommandException {
        //System.out.println("In NumberParameterType:parse() for class " + getReturnType().toGenericString());

        String input = buffer.next();
        if (input == null) {
            throw CommandException.missingArgument(parameter.getName());
        }

        T result;
        try {
            result = parse(input);
        } catch (Exception ex) {
            throw CommandException.invalidArgument(parameter.getName(), "a number");
        }

        Range.Memory memory = (Range.Memory) parameter.getParamInfo();
        if (memory != null) {
            memory.validate(result, "Argument " + parameter.getName() + " is out of range ["
                    + select(memory.min()) + ", " + select(memory.max()) + "]: " + result);
        }

        return result;
    }

    @Override
    public T getDefaultValue(Parameter<T, Range.Memory> parameter, CommandSender sender, ArgumentBuffer buffer) throws CommandException {
        Range.Memory memory = (Range.Memory) parameter.getParamInfo();
        if (memory != null) return select(memory.defaultValue());
        return !parameter.isPrimitive() ? null : select(0);
    }

}