1 package fr.ifremer.tutti.ui.swing.content.operation.catches.species.frequency;
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 import com.google.common.collect.Sets;
28 import org.apache.commons.lang3.mutable.MutableInt;
29
30 import java.io.Serializable;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Set;
34 import java.util.TreeMap;
35
36
37
38
39
40
41
42
43
44 public class SpeciesFrequencyUIModelCache implements Serializable {
45
46 private static final long serialVersionUID = 1L;
47
48
49
50
51
52
53 protected final Set<SpeciesFrequencyRowModel> withWeightRows = Sets.newHashSet();
54
55
56
57
58
59
60
61
62 protected final Map<Integer, MutableInt> nbOfRowsByLengthStep = new TreeMap<>();
63
64 private final Map<Float, SpeciesFrequencyRowModel> rowCache = new TreeMap<>();
65
66 public void loadCache(List<SpeciesFrequencyRowModel> rows) {
67
68 withWeightRows.clear();
69 nbOfRowsByLengthStep.clear();
70 rowCache.clear();
71
72 for (SpeciesFrequencyRowModel row : rows) {
73
74 Float lengthStep = row.getLengthStep();
75 if (lengthStep != null) {
76 rowCache.put(lengthStep, row);
77 incNumberOfRows(lengthStep);
78 }
79
80 updateRowWithWeight(row);
81
82 }
83
84 }
85
86 public void updateRowWithWeight(SpeciesFrequencyRowModel row) {
87
88 if (row.getWeight() == null) {
89 withWeightRows.remove(row);
90 } else {
91 withWeightRows.add(row);
92 }
93 }
94
95 public int getNbRowsWithWeight() {
96 return withWeightRows.size();
97 }
98
99 public int numberOfRows(float lengthStep) {
100 MutableInt mutableInt = getNbRowsByLengthStep(lengthStep);
101 return mutableInt.intValue();
102 }
103
104 public void incNumberOfRows(float lengthStep) {
105 MutableInt mutableInt = getNbRowsByLengthStep(lengthStep);
106 mutableInt.increment();
107 }
108
109 public void decNumberOfRows(float lengthStep) {
110 MutableInt mutableInt = getNbRowsByLengthStep(lengthStep);
111 mutableInt.decrement();
112 }
113
114 protected MutableInt getNbRowsByLengthStep(float lengthStep) {
115
116
117 int mmLengthStep = Math.round(lengthStep * 10);
118 MutableInt mutableInt = nbOfRowsByLengthStep.get(mmLengthStep);
119 if (mutableInt == null) {
120 mutableInt = new MutableInt(0);
121 nbOfRowsByLengthStep.put(mmLengthStep, mutableInt);
122 }
123 return mutableInt;
124
125 }
126
127 public void addLengthStep(SpeciesFrequencyRowModel row) {
128
129 Float lengthStep = row.getLengthStep();
130 rowCache.put(lengthStep, row);
131 incNumberOfRows(lengthStep);
132
133 }
134
135 public void removeLengthStep(Float oldValue) {
136
137 rowCache.remove(oldValue);
138 decNumberOfRows(oldValue);
139
140 }
141
142 public Map<Float, SpeciesFrequencyRowModel> getRowCache() {
143 return rowCache;
144 }
145
146
147 public Float computeTotalWeight() {
148 float result = 0f;
149 for (SpeciesFrequencyRowModel row : withWeightRows) {
150 if (!row.isValid()) {
151 continue;
152 }
153 result += row.getWeight();
154 }
155 return result;
156 }
157 }