1 | package com.framsticks.params; |
---|
2 | |
---|
3 | import java.util.Collections; |
---|
4 | import java.util.Iterator; |
---|
5 | import java.util.Map; |
---|
6 | |
---|
7 | import com.framsticks.structure.messages.ListChange; |
---|
8 | |
---|
9 | public class SimpleUniqueList<T extends UniqueObject> implements Iterable<T> { |
---|
10 | |
---|
11 | protected final Map<String, T> children; |
---|
12 | protected final Class<T> type; |
---|
13 | protected final char prefix; |
---|
14 | protected final EventListeners<ListChange> listeners = new EventListeners<>(); |
---|
15 | |
---|
16 | protected int counter = 0; |
---|
17 | |
---|
18 | /** |
---|
19 | * @param type |
---|
20 | */ |
---|
21 | public SimpleUniqueList(Class<T> type, char prefix) { |
---|
22 | this.type = type; |
---|
23 | this.prefix = prefix; |
---|
24 | children = UniqueListAccess.createMap(type, this); |
---|
25 | } |
---|
26 | |
---|
27 | // public static <T2> SimpleUniqueList<T2> make(Class<T2> type) { |
---|
28 | // return new SimpleUniqueList<T2>(type); |
---|
29 | // } |
---|
30 | |
---|
31 | public String generateId() { |
---|
32 | return prefix + Integer.toString(counter++); |
---|
33 | } |
---|
34 | |
---|
35 | @Override |
---|
36 | public Iterator<T> iterator() { |
---|
37 | return children.values().iterator(); |
---|
38 | } |
---|
39 | |
---|
40 | public void addListener(EventListener<ListChange> listener) { |
---|
41 | listeners.add(listener); |
---|
42 | } |
---|
43 | |
---|
44 | public void removeListener(EventListener<ListChange> listener) { |
---|
45 | listeners.remove(listener); |
---|
46 | } |
---|
47 | |
---|
48 | public void fireChildrenChange(ListChange original, ListChange.Action action, Object... hints) { |
---|
49 | listeners.actionForAll(new ListChange(action, original.getPosition(), original.getIdentifier(), hints)); |
---|
50 | |
---|
51 | } |
---|
52 | |
---|
53 | public void fireChildrenChange(T child, ListChange.Action action, Object... hints) { |
---|
54 | ListChange change = new ListChange(action, UniqueListAccess.getNumberInMap(children, child), child.getUid(), hints); |
---|
55 | listeners.actionForAll(change); |
---|
56 | } |
---|
57 | |
---|
58 | public void add(T child) { |
---|
59 | child.setUid(generateId()); |
---|
60 | children.put(child.getUid(), child); |
---|
61 | fireChildrenChange(child, ListChange.Action.Add); |
---|
62 | } |
---|
63 | |
---|
64 | public void remove(T child) { |
---|
65 | fireChildrenChange(child, ListChange.Action.Remove); |
---|
66 | children.remove(child.getUid()); |
---|
67 | } |
---|
68 | |
---|
69 | public void modify(T child) { |
---|
70 | fireChildrenChange(child, ListChange.Action.Modify); |
---|
71 | } |
---|
72 | |
---|
73 | public Map<String, T> getView() { |
---|
74 | return Collections.unmodifiableMap(children); |
---|
75 | } |
---|
76 | |
---|
77 | public Map<String, T> getMap() { |
---|
78 | return children; |
---|
79 | } |
---|
80 | } |
---|