View Javadoc
1   package fr.ifremer.dali.ui.swing.content.observation.operation.measurement;
2   
3   /*
4    * #%L
5    * Dali :: UI
6    * $Id:$
7    * $HeadURL:$
8    * %%
9    * Copyright (C) 2014 - 2015 Ifremer
10   * %%
11   * This program is free software: you can redistribute it and/or modify
12   * it under the terms of the GNU Affero General Public License as published by
13   * the Free Software Foundation, either version 3 of the License, or
14   * (at your option) any later version.
15   *
16   * This program is distributed in the hope that it will be useful,
17   * but WITHOUT ANY WARRANTY; without even the implied warranty of
18   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19   * GNU General Public License for more details.
20   *
21   * You should have received a copy of the GNU Affero General Public License
22   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23   * #L%
24   */
25  
26  import com.google.common.base.Predicate;
27  import com.google.common.collect.Lists;
28  import fr.ifremer.dali.decorator.DecoratorService;
29  import fr.ifremer.dali.dto.DaliBeans;
30  import fr.ifremer.dali.dto.configuration.programStrategy.PmfmStrategyDTO;
31  import fr.ifremer.dali.dto.data.sampling.SamplingOperationDTO;
32  import fr.ifremer.dali.dto.referential.pmfm.PmfmDTO;
33  import fr.ifremer.dali.ui.swing.content.observation.ObservationUIModel;
34  import fr.ifremer.dali.ui.swing.content.observation.operation.measurement.grouped.OperationMeasurementsFilter;
35  import fr.ifremer.dali.ui.swing.content.observation.operation.measurement.grouped.OperationMeasurementsGroupedTableUIModel;
36  import fr.ifremer.dali.ui.swing.content.observation.operation.measurement.ungrouped.OperationMeasurementsUngroupedTableUIModel;
37  import fr.ifremer.dali.ui.swing.util.AbstractDaliBeanUIModel;
38  import fr.ifremer.dali.ui.swing.util.AbstractDaliUIHandler;
39  import fr.ifremer.dali.ui.swing.util.DaliUIs;
40  import jaxx.runtime.SwingUtil;
41  import jaxx.runtime.validator.swing.SwingValidator;
42  import org.apache.commons.collections4.CollectionUtils;
43  import org.nuiton.jaxx.application.swing.tab.TabHandler;
44  
45  import java.util.List;
46  import java.util.stream.Collectors;
47  
48  /**
49   * Controlleur pour l'onglet prelevements mesures.
50   */
51  public class OperationMeasurementsTabUIHandler extends AbstractDaliUIHandler<OperationMeasurementsTabUIModel, OperationMeasurementsTabUI> implements TabHandler {
52  
53      /**
54       * {@inheritDoc}
55       */
56      @Override
57      public void beforeInit(OperationMeasurementsTabUI ui) {
58          super.beforeInit(ui);
59  
60          // create model and register to the JAXX context
61          final OperationMeasurementsTabUIModel model = new OperationMeasurementsTabUIModel();
62          ui.setContextValue(model);
63  
64      }
65  
66      /**
67       * {@inheritDoc}
68       */
69      @Override
70      public void afterInit(OperationMeasurementsTabUI ui) {
71          initUI(ui);
72  
73          // init comboboxes
74          initComboBox();
75  
76          getModel().setUngroupedTableUIModel(getUI().getUngroupedTable().getModel());
77          getModel().setGroupedTableUIModel(getUI().getGroupedTable().getModel());
78  
79          // init image
80          SwingUtil.setComponentWidth(getUI().getLeftImage(), ui.getMenuPanel().getPreferredSize().width * 9 / 10);
81          getUI().getLeftImage().setScaled(true);
82  
83          // Initialiser listeners
84          initListeners();
85  
86          registerValidators(getValidator());
87          listenValidatorValid(getValidator(), getModel());
88      }
89  
90      /**
91       * Initialisation des combobox
92       */
93      private void initComboBox() {
94  
95          // Initialisation des prelevements
96          initBeanFilterableComboBox(
97              getUI().getSelectionPrelevementsCombo(),
98              getModel().getSamplings(),
99              getModel().getSampling(),
100             DecoratorService.CONCAT);
101 
102         /*
103         // Initialisation des groupe de taxons
104         initBeanFilterableComboBox(
105                 getUI().getSelectionGroupeTaxonCombo(),
106                 null,
107                 null, DecoratorService.NAME);
108 
109         getUI().getSelectionGroupeTaxonCombo().setActionEnabled(getContext().getDataContext().isContextFiltered(FilterTypeValues.TAXON_GROUP));
110         getUI().getSelectionGroupeTaxonCombo().setActionListener(new ActionListener() {
111             @Override
112             public void actionPerformed(ActionEvent e) {
113                 if (!askBefore(t("dali.common.unfilter"), t("dali.common.unfilter.confirmation"))) {
114                     return;
115                 }
116                 updateTaxonGroupComboBox(getModel().getTaxon(), true);
117             }
118         });
119         updateTaxonGroupComboBox(null, false);
120 
121         // Intialisation des taxons
122         initBeanFilterableComboBox(
123                 getUI().getSelectionTaxonCombo(),
124                 null,
125                 null);
126 
127         getUI().getSelectionTaxonCombo().setActionEnabled(getContext().getDataContext().isContextFiltered(FilterTypeValues.TAXON));
128         getUI().getSelectionTaxonCombo().setActionListener(new ActionListener() {
129             @Override
130             public void actionPerformed(ActionEvent e) {
131                 if (!askBefore(t("dali.common.unfilter"), t("dali.common.unfilter.confirmation"))) {
132                     return;
133                 }
134                 updateTaxonComboBox(getModel().getTaxonGroup(), true);
135             }
136         });
137         updateTaxonComboBox(null, false);
138 */
139 
140         DaliUIs.forceComponentSize(getUI().getSelectionPrelevementsCombo());
141 //        DaliUIs.forceComponentSize(getUI().getSelectionGroupeTaxonCombo());
142 //        DaliUIs.forceComponentSize(getUI().getSelectionTaxonCombo());
143     }
144 
145     /**
146      * Initialiser listeners de l ecran.
147      */
148     private void initListeners() {
149 
150         getModel().addPropertyChangeListener(OperationMeasurementsTabUIModel.PROPERTY_OBSERVATION_MODEL, evt -> load(getModel().getObservationModel()));
151 
152         // add model listener on selected sampling operation
153         getModel().addPropertyChangeListener(OperationMeasurementsTabUIModel.PROPERTY_SAMPLING, evt -> {
154 
155             if (getModel().isAdjusting()) return;
156             // reset context value
157             getContext().setSelectedSamplingOperationId(getModel().getSampling() != null ? getModel().getSampling().getId() : null);
158         });
159 
160         // add model listener on taxon group to filter taxons
161 //        getModel().addPropertyChangeListener(OperationMeasurementsTabUIModel.PROPERTY_TAXON_GROUP, new PropertyChangeListener() {
162 //
163 //            @Override
164 //            public void propertyChange(PropertyChangeEvent evt) {
165 //                if (getModel().isAdjusting()) return;
166 //                getModel().setAdjusting(true);
167 //                updateTaxonComboBox(evt.getNewValue() == null ? null : (TaxonGroupDTO) evt.getNewValue(), false);
168 //                getModel().setAdjusting(false);
169 //            }
170 //        });
171 //        getModel().addPropertyChangeListener(OperationMeasurementsTabUIModel.PROPERTY_TAXON, new PropertyChangeListener() {
172 //            @Override
173 //            public void propertyChange(PropertyChangeEvent evt) {
174 //                if (getModel().isAdjusting()) return;
175 //                getModel().setAdjusting(true);
176 //                updateTaxonGroupComboBox(evt.getNewValue() == null ? null : (TaxonDTO) evt.getNewValue(), false);
177 //                getModel().setAdjusting(false);
178 //            }
179 //        });
180 
181         // Add listeners on PROPERTY_ROWS_IN_ERROR to catch modifications and revalidate
182         getModel().getUngroupedTableUIModel().addPropertyChangeListener(OperationMeasurementsUngroupedTableUIModel.PROPERTY_ROWS_IN_ERROR, evt -> {
183             // re validate
184             getValidator().doValidate();
185         });
186         getModel().getGroupedTableUIModel().addPropertyChangeListener(OperationMeasurementsGroupedTableUIModel.PROPERTY_ROWS_IN_ERROR, evt -> {
187             // re validate
188             getValidator().doValidate();
189         });
190 
191         // Add listener on loading property and propagate to children
192         getModel().addPropertyChangeListener(AbstractDaliBeanUIModel.PROPERTY_LOADING, evt -> {
193             getModel().getUngroupedTableUIModel().setLoading((Boolean) evt.getNewValue());
194             getModel().getGroupedTableUIModel().setLoading((Boolean) evt.getNewValue());
195         });
196 
197         // Listen tables models
198         listenModelModify(getModel().getUngroupedTableUIModel());
199         listenModelModify(getModel().getGroupedTableUIModel());
200 
201     }
202 
203     /*
204     private void updateTaxonGroupComboBox(TaxonDTO taxon, boolean forceNoFilter) {
205 
206         getUI().getSelectionGroupeTaxonCombo().setActionEnabled(!forceNoFilter && getContext().getDataContext().isContextFiltered(FilterTypeValues.TAXON_GROUP));
207 
208         List<TaxonGroupDTO> taxonGroups = getContext().getObservationService().getAvailableTaxonGroups(taxon, forceNoFilter);
209         getUI().getSelectionGroupeTaxonCombo().setData(taxonGroups);
210 
211         if (CollectionUtils.isEmpty(taxonGroups) && getModel().getTaxonGroup() != null) {
212             getModel().setTaxonGroup(null);
213         } else if (taxonGroups.size() == 1) {
214             getModel().setTaxonGroup(taxonGroups.get(0));
215         }
216 
217     }
218 
219     private void updateTaxonComboBox(TaxonGroupDTO taxonGroup, boolean forceNoFilter) {
220 
221         getUI().getSelectionTaxonCombo().setActionEnabled(!forceNoFilter && getContext().getDataContext().isContextFiltered(FilterTypeValues.TAXON));
222 
223         List<TaxonDTO> taxons = getContext().getObservationService().getAvailableTaxons(taxonGroup, forceNoFilter);
224         getUI().getSelectionTaxonCombo().setData(taxons);
225 
226         if (CollectionUtils.isEmpty(taxons) && getModel().getTaxon() != null) {
227             getModel().setTaxon(null);
228         } else if (taxons.size() == 1) {
229             getModel().setTaxon(taxons.get(0));
230         }
231 
232     }
233     */
234 
235     /**
236      * {@inheritDoc}
237      */
238     @Override
239     public SwingValidator<OperationMeasurementsTabUIModel> getValidator() {
240         return getUI().getValidator();
241     }
242 
243     /**
244      * Load observation.
245      *
246      * @param survey Observation
247      */
248     private void load(final ObservationUIModel survey) {
249 
250         if (survey == null || survey.getId() == null) {
251             return;
252         }
253 
254         getModel().setAdjusting(true);
255 
256         List<PmfmStrategyDTO> pmfmStrategies = DaliBeans.filterCollection(survey.getPmfmStrategies(), (Predicate<PmfmStrategyDTO>) input -> input != null && input.isSampling());
257 
258         // list available samplings
259         getUI().getSelectionPrelevementsCombo().setData(getModel().getSamplings());
260 
261         // Load ungrouped data (up table)
262         {
263 
264             // load pmfms for ungrouped measurements
265             List<PmfmDTO> pmfms = pmfmStrategies.stream()
266                 .filter(pmfmStrategy -> !pmfmStrategy.isGrouping())
267                 .map(PmfmStrategyDTO::getPmfm)
268                 .collect(Collectors.toList());
269 
270             // Load other Pmfms in sampling operations
271             if (CollectionUtils.isNotEmpty(getModel().getSamplings())) {
272                 // populate pmfms from strategy to sampling operation and vice versa
273                 getModel().getSamplings().forEach(samplingOperation -> DaliBeans.fillListsEachOther(samplingOperation.getPmfms(), pmfms));
274             }
275 
276             // Set model properties
277             getModel().getUngroupedTableUIModel().setPmfms(pmfms);
278 
279             getModel().getUngroupedTableUIModel().setSurvey(survey);
280         }
281 
282         // Load grouped data (down table)
283         {
284 
285             List<PmfmDTO> individualPmfms = Lists.newArrayList();
286             // find pmfms having taxon unique constraint in strategy
287             List<PmfmDTO> uniquePmfms = Lists.newArrayList();
288             for (PmfmStrategyDTO pmfmStrategy : pmfmStrategies) {
289                 if (pmfmStrategy.isGrouping()) {
290                     individualPmfms.add(pmfmStrategy.getPmfm());
291                     if (pmfmStrategy.isUnique()) {
292                         uniquePmfms.add(pmfmStrategy.getPmfm());
293                     }
294                 }
295             }
296 
297             // Load other Pmfms in sampling operations
298             if (CollectionUtils.isNotEmpty(getModel().getSamplings())) {
299                 // populate pmfms from strategy to sampling operation and vice versa
300                 getModel().getSamplings().forEach(samplingOperation -> DaliBeans.fillListsEachOther(samplingOperation.getIndividualPmfms(), individualPmfms));
301             }
302 
303             // Set model properties
304             getModel().getGroupedTableUIModel().setPmfms(individualPmfms);
305             getModel().getGroupedTableUIModel().setUniquePmfms(uniquePmfms);
306 
307             getModel().getGroupedTableUIModel().setSurvey(survey);
308         }
309 
310         //update selected sampling
311         if (getContext().getSelectedSamplingOperationId() != null && getModel().getSamplings() != null) {
312             for (SamplingOperationDTO samplingOperation : getModel().getSamplings()) {
313                 if (getContext().getSelectedSamplingOperationId().equals(samplingOperation.getId())) {
314                     getModel().setSampling(samplingOperation);
315                     break;
316                 }
317             }
318         }
319 
320         // Disable this Tab to avoid bad behavior is no sampling found
321         if (CollectionUtils.isEmpty(getModel().getSamplings())) {
322             setEnabled(getUI(), false);
323         }
324 
325         // execute doSearch to simulate loading measurements data
326         doSearch();
327 
328         getModel().setAdjusting(false);
329     }
330 
331     /**
332      * <p>clearSearch.</p>
333      */
334     public void clearSearch() {
335 
336         // Suppression choix du groupe de taxons
337 //        getModel().setTaxonGroup(null);
338 
339         // Suppression choix du taxon
340 //        getModel().setTaxon(null);
341 
342         // Suppression choix prelevement
343         getModel().setSampling(null);
344 
345     }
346 
347     /**
348      * <p>doSearch.</p>
349      */
350     public void doSearch() {
351 
352         // set taxon group and taxon filter
353         getModel().getUngroupedTableUIModel().setSamplingFilter(getModel().getSampling());
354 
355         OperationMeasurementsFilter measurementFilter = new OperationMeasurementsFilter();
356 //        measurementFilter.setTaxonGroup(getModel().getTaxonGroup());
357 //        measurementFilter.setTaxon(getModel().getTaxon());
358         measurementFilter.setSamplingOperation(getModel().getSampling());
359         getModel().getGroupedTableUIModel().setMeasurementFilter(measurementFilter);
360     }
361 
362     public void save() {
363 
364         try {
365 
366             // Disable filter
367             getModel().getUngroupedTableUIModel().setSamplingFilter(null);
368             getModel().getGroupedTableUIModel().setMeasurementFilter(null);
369 
370             // save ungrouped measurements
371             getUI().getUngroupedTable().getHandler().save();
372 
373             // save grouped measurements
374             getUI().getGroupedTable().getHandler().save();
375 
376         } finally {
377 
378             doSearch();
379         }
380     }
381 
382     /**
383      * {@inheritDoc}
384      */
385     @Override
386     public boolean onHideTab(int currentIndex, int newIndex) {
387         return true;
388     }
389 
390     /**
391      * {@inheritDoc}
392      */
393     @Override
394     public void onShowTab(int currentIndex, int newIndex) {
395     }
396 
397     /**
398      * {@inheritDoc}
399      */
400     @Override
401     public boolean onRemoveTab() {
402         return false;
403     }
404 
405 }