aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/dev/isxander/yacl3/impl/SimpleStateManager.java
blob: e9c72750722bb4aeb365ad72463d07a1c307d9a2 (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
57
58
59
60
61
62
63
64
65
package dev.isxander.yacl3.impl;

import dev.isxander.yacl3.api.Binding;
import dev.isxander.yacl3.api.StateManager;

public class SimpleStateManager<T> implements StateManager<T>, ProvidesBindingForDeprecation<T> {
    private T pendingValue;
    private final Binding<T> binding;
    private StateListener<T> stateListener;

    public SimpleStateManager(Binding<T> binding) {
        this.binding = binding;
        this.pendingValue = binding.getValue();
        this.stateListener = StateListener.noop();
    }

    @Override
    public void set(T value) {
        boolean changed = !this.pendingValue.equals(value);

        this.pendingValue = value;

        if (changed) stateListener.onStateChange(this.pendingValue, value);
    }

    @Override
    public T get() {
        return pendingValue;
    }

    @Override
    public void apply() {
        binding.setValue(pendingValue);
    }

    @Override
    public void resetToDefault(ResetAction action) {
        this.set(binding.defaultValue());
    }

    @Override
    public void sync() {
        this.set(binding.getValue());
    }

    @Override
    public boolean isSynced() {
        return binding.getValue().equals(pendingValue);
    }

    @Override
    public boolean isDefault() {
        return binding.defaultValue().equals(pendingValue);
    }

    @Override
    public void addListener(StateListener<T> stateListener) {
        this.stateListener = this.stateListener.andThen(stateListener);
    }

    @Override
    public Binding<T> getBinding() {
        return binding;
    }
}