View Javadoc
1   package fr.ifremer.reefdb.ui.swing.content.observation;
2   
3   /*
4    * #%L
5    * Reef DB :: 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 fr.ifremer.reefdb.dto.ReefDbBeans;
27  import fr.ifremer.reefdb.dto.data.survey.SurveyDTO;
28  import fr.ifremer.reefdb.dto.referential.TaxonDTO;
29  import fr.ifremer.reefdb.dto.referential.TaxonGroupDTO;
30  import fr.ifremer.reefdb.service.ReefDbTechnicalException;
31  import fr.ifremer.reefdb.ui.swing.action.GoToObservationAction;
32  import fr.ifremer.reefdb.ui.swing.action.QuitScreenAction;
33  import fr.ifremer.reefdb.ui.swing.util.ReefDbUIs;
34  import fr.ifremer.reefdb.ui.swing.util.tab.AbstractReefDbTabContainerUIHandler;
35  import fr.ifremer.reefdb.ui.swing.util.tab.ReefDbTabIndexes;
36  import jaxx.runtime.SwingUtil;
37  import org.apache.commons.collections4.CollectionUtils;
38  import org.apache.commons.logging.Log;
39  import org.apache.commons.logging.LogFactory;
40  import org.nuiton.jaxx.application.swing.util.CloseableUI;
41  
42  import javax.swing.BorderFactory;
43  import javax.swing.JTabbedPane;
44  import javax.swing.SwingWorker;
45  import java.awt.Color;
46  import java.util.List;
47  import java.util.concurrent.ExecutionException;
48  
49  import static org.nuiton.i18n.I18n.t;
50  
51  /**
52   * Controlleur pour observation.
53   */
54  public class ObservationUIHandler extends AbstractReefDbTabContainerUIHandler<ObservationUIModel, ObservationUI> implements CloseableUI {
55  
56      /**
57       * Logger.
58       */
59      private static final Log LOG = LogFactory.getLog(ObservationUIHandler.class);
60  
61      /**
62       * {@inheritDoc}
63       */
64      @Override
65      public void beforeInit(final ObservationUI ui) {
66          super.beforeInit(ui);
67  
68          // Create model and register to the JAXX context
69          final ObservationUIModel model = new ObservationUIModel();
70          ui.setContextValue(model);
71  
72      }
73  
74      /**
75       * {@inheritDoc}
76       */
77      @Override
78      public void afterInit(final ObservationUI ui) {
79  
80          initUI(ui);
81          SwingUtil.setLayerUI(getTabPanel(), ui.getSurveyBlockLayer());
82  
83          // Affect models
84          getModel().setSurveyDetailsTabUIModel(getUI().getSurveyDetailsTabUI().getModel());
85          getModel().setSurveyMeasurementsTabUIModel(getUI().getSurveyMeasurementsTabUI().getModel());
86          getModel().setOperationMeasurementsTabUIModel(getUI().getOperationMeasurementsTabUI().getModel());
87          getModel().setPhotosTabUIModel(getUI().getPhotosTabUI().getModel());
88  
89          // Add main handler to other model (Mantis #48309)
90          getModel().getSurveyMeasurementsTabUIModel().setObservationHandler(this);
91          getModel().getOperationMeasurementsTabUIModel().setObservationHandler(this);
92  
93          // Ajout des onglets
94          setCustomTab(ReefDbTabIndexes.ONGLET_OBSERVATION_GENERAL, getModel().getSurveyDetailsTabUIModel());
95          setCustomTab(ReefDbTabIndexes.ONGLET_OBSERVATION_MESURES, getModel().getSurveyMeasurementsTabUIModel());
96          setCustomTab(ReefDbTabIndexes.ONGLET_PRELEVEMENTS_MESURES, getModel().getOperationMeasurementsTabUIModel());
97          setCustomTab(ReefDbTabIndexes.ONGLET_PHOTOS, getModel().getPhotosTabUIModel());
98  
99          // set label colors
100         ReefDbUIs.setChildrenLabelForeground(ui, getConfig().getColorThematicLabel());
101         ui.getObservationDescriptionLabel().setForeground(Color.BLACK);
102 
103         // Selection de l onglet actif
104         getTabPanel().setSelectedIndex(getUI().getTabIndex());
105 
106         // Binding save button
107         getUI().applyDataBinding(ObservationUI.BINDING_SAVE_BUTTON_ENABLED);
108 
109         // button border
110         getUI().getNextButton().setBorder(
111                 BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, getConfig().getColorHighlightButtonBorder()), ui.getNextButton().getBorder())
112         );
113 
114         // Listen modify
115         listenModelModify(getModel().getSurveyDetailsTabUIModel());
116         listenModelModify(getModel().getSurveyMeasurementsTabUIModel());
117         listenModelModify(getModel().getOperationMeasurementsTabUIModel());
118         listenModelModify(getModel().getPhotosTabUIModel());
119 
120         // Listen valid
121         listenModelValid(getModel().getSurveyDetailsTabUIModel());
122         listenModelValid(getModel().getSurveyMeasurementsTabUIModel());
123         listenModelValid(getModel().getOperationMeasurementsTabUIModel());
124         listenModelValid(getModel().getPhotosTabUIModel());
125 
126         // REgister validators
127         registerValidators(
128                 getUI().getSurveyDetailsTabUI().getValidator(),
129                 getUI().getSurveyMeasurementsTabUI().getValidator(),
130                 getUI().getOperationMeasurementsTabUI().getValidator(),
131                 getUI().getPhotosTabUI().getValidator());
132 
133         // listener on properties that updates the title
134         getModel().addPropertyChangeListener(evt -> {
135             if (ObservationUIModel.PROPERTY_LOCATION.equals(evt.getPropertyName())
136                     || ObservationUIModel.PROPERTY_DATE.equals(evt.getPropertyName())
137                     || ObservationUIModel.PROPERTY_TIME.equals(evt.getPropertyName())
138                     || ObservationUIModel.PROPERTY_PROGRAM.equals(evt.getPropertyName())
139                     || ObservationUIModel.PROPERTY_NAME.equals(evt.getPropertyName())
140             ) {
141                 getUI().applyDataBinding(ObservationUI.BINDING_OBSERVATION_DESCRIPTION_LABEL_TEXT);
142             }
143         });
144 
145         // load model
146         loadSurvey();
147 
148     }
149 
150     /**
151      * {@inheritDoc}
152      */
153     @Override
154     public String getTitle() {
155         String contextName;
156         if (getContext().getSelectedContext() == null) {
157             contextName = t("reefdb.main.title.noContext");
158         } else {
159             contextName = getContext().getSelectedContext().getName();
160         }
161 
162         return String.format("%s [%s]", super.getTitle(), contextName);
163     }
164 
165     private void loadSurvey() {
166 
167         getModel().setLoading(true);
168         SurveyLoader loader = new SurveyLoader();
169         loader.execute();
170 
171     }
172 
173     /**
174      * Select next available tab
175      */
176     void selectNextTab() {
177 
178         int index = getTabPanel().getSelectedIndex() + 1;
179 
180         if (index >= getTabPanel().getTabCount()) {
181             // if last tab is reached, return to HomeUI
182             changeScreenAction(GoToObservationAction.class);
183         }
184 
185         while (index < getTabPanel().getTabCount()) {
186             if (getTabPanel().isEnabledAt(index)) {
187                 getTabPanel().setSelectedIndex(index);
188                 return;
189             }
190             index++;
191         }
192     }
193 
194     /**
195      * <p>refreshModels.</p>
196      */
197     void refreshModels() {
198 
199         // force components to update enabled state if survey is editable or not
200         getModel().getSurveyDetailsTabUIModel().setEditable(getModel().isEditable());
201 
202         // TODO add other models
203         getModel().getSurveyMeasurementsTabUIModel().setObservationModel(getModel());
204         getModel().getOperationMeasurementsTabUIModel().setObservationModel(getModel());
205 
206         getModel().getPhotosTabUIModel().setObservationModel(getModel());
207     }
208 
209     public List<TaxonDTO> getAvailableTaxons(TaxonGroupDTO taxonGroup, boolean forceNoContext) {
210 
211         if (taxonGroup == null) {
212 
213             // if no taxon group specified, means that all available taxons will be returned
214 
215             // check first if the list is not already set or the context has changed
216             if (CollectionUtils.isEmpty(getModel().getAllAvailableTaxons())
217                     || getModel().getForceNoContextOnTaxons() == null
218                     || getModel().getForceNoContextOnTaxons() != forceNoContext) {
219 
220                 // the list is filled or the context have changed
221                 getModel().setForceNoContextOnTaxons(forceNoContext);
222                 getModel().setAllAvailableTaxons(
223                         getContext().getObservationService().getAvailableTaxons(forceNoContext)
224                 );
225             }
226             // return existing list
227             return getModel().getAllAvailableTaxons();
228 
229         } else {
230 
231             // call service directly if taxon group specified (use now as reference date (see Mantis #45148)
232             return getContext().getObservationService().getAvailableTaxons(taxonGroup, forceNoContext);
233         }
234     }
235 
236     public List<TaxonGroupDTO> getAvailableTaxonGroups(TaxonDTO taxon, boolean forceNoContext) {
237 
238         if (taxon == null) {
239 
240             // if no taxon specified, means that all available taxon groups will be returned
241 
242             // check first if the list is not already set or the context has changed
243             if (CollectionUtils.isEmpty(getModel().getAllAvailableTaxonGroups())
244                     || getModel().getForceNoContextOnTaxonGroups() == null
245                     || getModel().getForceNoContextOnTaxonGroups() != forceNoContext) {
246 
247                 // the list is filled or the context have changed
248                 getModel().setForceNoContextOnTaxonGroups(forceNoContext);
249                 getModel().setAllAvailableTaxonGroups(
250                         getContext().getObservationService().getAvailableTaxonGroups(forceNoContext)
251                 );
252             }
253             // return existing list
254             return getModel().getAllAvailableTaxonGroups();
255 
256         } else {
257 
258             // call service directly if taxon group specified (use now as reference date (see Mantis #45148)
259             return getContext().getObservationService().getAvailableTaxonGroups(taxon, forceNoContext);
260         }
261     }
262 
263     /**
264      * {@inheritDoc}
265      */
266     @Override
267     public JTabbedPane getTabPanel() {
268         return getUI().getObservationTabbedPane();
269     }
270 
271     /**
272      * {@inheritDoc}
273      */
274     @Override
275     public boolean removeTab(int i) {
276         return false;
277     }
278 
279     /**
280      * {@inheritDoc}
281      */
282     @Override
283     @SuppressWarnings("unchecked")
284     public boolean quitUI() {
285         try {
286             QuitScreenAction action = new QuitScreenAction(this, false, SaveAction.class);
287             if (action.prepareAction()) {
288                 return true;
289             }
290         } catch (Exception e) {
291             LOG.error(e.getLocalizedMessage(), e);
292         }
293         return false;
294     }
295 
296     private class SurveyLoader extends SwingWorker<Object, Object> {
297 
298         @Override
299         protected Object doInBackground() {
300 
301             // Observation
302             final SurveyDTO survey = getContext().getObservationService().getSurvey(getContext().getSelectedSurveyId());
303 
304             // Prepare editable state for general tab to speed up some behaviours
305             getModel().setEditable(!ReefDbBeans.isSurveyValidated(survey));
306             getModel().getSurveyDetailsTabUIModel().setEditable(getModel().isEditable());
307 
308             // load observation into parent model (this)
309             getModel().fromBean(survey);
310 
311             // load pmfm strategies
312             getModel().setPmfmStrategies(getContext().getProgramStrategyService().getPmfmStrategiesBySurvey(survey));
313 
314             // load preconditioned rules
315             getModel().setPreconditionedRules(getContext().getRuleListService().getPreconditionedControlRulesForSurvey(survey));
316 
317             // load grouped rules
318             getModel().setGroupedRules(getContext().getRuleListService().getGroupedControlRulesForSurvey(survey));
319 
320             // affect other models
321             refreshModels();
322 
323             return null;
324         }
325 
326         @Override
327         protected void done() {
328             try {
329                 try {
330                     get();
331                 } catch (InterruptedException | ExecutionException e) {
332                     throw new ReefDbTechnicalException(e.getMessage(), e);
333                 }
334 
335                 getUI().applyDataBinding(ObservationUI.BINDING_OBSERVATION_DESCRIPTION_LABEL_TEXT);
336 
337                 // Reset modify flag
338                 getModel().setModify(false);
339 
340             } finally {
341                 getModel().setLoading(false);
342             }
343         }
344     }
345 
346 }