View Javadoc
1   package fr.ifremer.dali.ui.swing.content.extraction;
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.collect.Sets;
27  import fr.ifremer.dali.dto.DaliBeans;
28  import fr.ifremer.dali.dto.configuration.programStrategy.PmfmStrategyDTO;
29  import fr.ifremer.dali.dto.enums.ExtractionFilterTypeValues;
30  import fr.ifremer.dali.dto.referential.pmfm.PmfmDTO;
31  import fr.ifremer.dali.dto.system.extraction.ExtractionDTO;
32  import fr.ifremer.dali.dto.system.extraction.ExtractionPeriodDTO;
33  import fr.ifremer.dali.ui.swing.action.QuitScreenAction;
34  import fr.ifremer.dali.ui.swing.content.extraction.filters.ExtractionFiltersUIModel;
35  import fr.ifremer.dali.ui.swing.content.extraction.list.ExtractionsRowModel;
36  import fr.ifremer.dali.ui.swing.content.extraction.list.ExtractionsTableUIModel;
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.logging.Log;
43  import org.apache.commons.logging.LogFactory;
44  import org.nuiton.jaxx.application.swing.util.CloseableUI;
45  
46  import javax.swing.SwingUtilities;
47  import java.util.*;
48  import java.util.stream.Collectors;
49  
50  /**
51   * Extraction handler.
52   */
53  public class ExtractionUIHandler extends AbstractDaliUIHandler<ExtractionUIModel, ExtractionUI> implements CloseableUI {
54  
55      /**
56       * Logger.
57       */
58      private static final Log LOG = LogFactory.getLog(ExtractionUIHandler.class);
59  
60      /** {@inheritDoc} */
61      @Override
62      public void beforeInit(final ExtractionUI ui) {
63          super.beforeInit(ui);
64  
65          // Ajout du model pour la page d acceuil
66          final ExtractionUIModel model = new ExtractionUIModel();
67          ui.setContextValue(model);
68  
69          ui.setContextValue(SwingUtil.createActionIcon("export"));
70  
71      }
72  
73      /** {@inheritDoc} */
74      @Override
75      public void afterInit(ExtractionUI ui) {
76          initUI(ui);
77          ui.getSelectExtractionLabel().setForeground(getConfig().getColorThematicLabel());
78          ui.getSelectProgramLabel().setForeground(getConfig().getColorThematicLabel());
79  
80          // Save models
81          getModel().setExtractionsTableUIModel(getUI().getExtractionsTable().getModel());
82          getModel().setExtractionFiltersUIModel(getUI().getFiltersTable().getModel());
83          getModel().setExtractionConfigUIModel(getUI().getConfigUI().getModel());
84  
85          // Initialisation des combobox
86          initComboBox();
87  
88          // Initialisation des listeners
89          initListeners();
90  
91          // Register validator
92          registerValidators(getValidator());
93          listenValidatorValid(getValidator(), getModel());
94  
95          // init image
96          SwingUtil.setComponentWidth(getUI().getLeftImage(), ui.getExtractionMenu().getPreferredSize().width * 9 / 10);
97          getUI().getLeftImage().setScaled(true);
98  
99          getModel().setModify(false);
100     }
101 
102     /**
103      * Initialisation des composants de gauche
104      */
105     private void initComboBox() {
106 
107         // Init context combo
108         initBeanFilterableComboBox(
109                 getUI().getContextComboBox(),
110                 getContext().getContextService().getAllContexts(),
111                 getContext().getSelectedContext());
112 
113         // Init extractions combo
114         initBeanFilterableComboBox(
115                 getUI().getSelectExtractionCombo(),
116                 getContext().getExtractionService().getAllLightExtractions(),
117                 null);
118 
119         // Init programs combo
120         initBeanFilterableComboBox(
121                 getUI().getSelectProgramCombo(),
122                 getContext().getObservationService().getAvailablePrograms(null, null, false),
123                 null);
124 
125         // Modification des largeurs des combobox
126         DaliUIs.forceComponentSize(getUI().getContextComboBox());
127         DaliUIs.forceComponentSize(getUI().getSelectExtractionCombo());
128         DaliUIs.forceComponentSize(getUI().getSelectProgramCombo());
129 
130         getUI().getSelectExtractionCombo().getComboBoxModel().addWillChangeSelectedItemListener(event -> {
131             if (getModel().isLoading()) return;
132             if (event.getNextSelectedItem() != null) SwingUtilities.invokeLater(() -> getUI().getSearchButton().getAction().actionPerformed(null));
133         });
134     }
135 
136     /**
137      * <p>reloadComboBox.</p>
138      */
139     public void reloadComboBox() {
140         getModel().setLoading(true);
141         getUI().getSelectExtractionCombo().setData(getContext().getExtractionService().getAllLightExtractions());
142         getModel().setLoading(false);
143     }
144 
145     /**
146      * Initialiser les listeners.
147      */
148     private void initListeners() {
149 
150         // Listen modify property and set dirty to the selected program
151         listenModelModify(getModel().getExtractionsTableUIModel());
152         getModel().getExtractionFiltersUIModel().addPropertyChangeListener(AbstractDaliBeanUIModel.PROPERTY_MODIFY, evt -> {
153             Boolean modify = (Boolean) evt.getNewValue();
154             if (!getModel().getExtractionFiltersUIModel().isLoading() && modify != null) {
155                 getModel().setModify(modify);
156                 if (modify && getModel().getSelectedExtraction() != null) {
157                     getModel().getSelectedExtraction().setDirty(true);
158                 }
159             }
160         });
161         getModel().getExtractionConfigUIModel().addPropertyChangeListener(AbstractDaliBeanUIModel.PROPERTY_MODIFY, evt -> {
162             Boolean modify = (Boolean) evt.getNewValue();
163             if (!getModel().getExtractionConfigUIModel().isLoading() && modify != null) {
164                 getModel().setModify(modify);
165                 ExtractionsRowModel selectedExtraction = getModel().getSelectedExtraction();
166                 if (modify && selectedExtraction != null) {
167                     selectedExtraction.setParameter(getModel().getExtractionConfigUIModel().toBean());
168                     selectedExtraction.setDirty(true);
169                 }
170             }
171         });
172 
173         // Listen when a extraction is selected by table
174         // Listener on selection
175         getModel().getExtractionsTableUIModel().addPropertyChangeListener(ExtractionsTableUIModel.PROPERTY_SINGLE_ROW_SELECTED, evt -> {
176             getUI().getFiltersTable().getHandler().loadFilters();
177             getUI().getConfigUI().getHandler().loadConfig();
178         });
179 
180         getModel().getExtractionsTableUIModel().addPropertyChangeListener(AbstractDaliBeanUIModel.PROPERTY_VALID, evt -> getValidator().doValidate());
181         getModel().getExtractionFiltersUIModel().addPropertyChangeListener(AbstractDaliBeanUIModel.PROPERTY_VALID, evt -> {
182             Boolean valid = (Boolean) evt.getNewValue();
183             ExtractionsRowModel extractionRow = getModel().getSelectedExtraction();
184             if (extractionRow != null) {
185 
186                 // set filters valid state on current selected extraction
187                 extractionRow.setFiltersValid(valid);
188 
189                 // enable config UI
190                 getModel().getExtractionConfigUIModel().setEnabled(valid);
191 
192                 getUI().getExtractionsTable().getHandler().recomputeRowValidState(extractionRow);
193                 getValidator().doValidate();
194             } else {
195 
196                 // disable config UI
197                 getModel().getExtractionConfigUIModel().setEnabled(false);
198 
199             }
200         });
201 
202         // listener on program selection
203         getModel().addPropertyChangeListener(ExtractionUIModel.PROPERTY_PROGRAM, evt -> {
204             // TODO ?
205         });
206 
207         // propagate loading property
208         getModel().getExtractionFiltersUIModel().addPropertyChangeListener(ExtractionFiltersUIModel.PROPERTY_LOADING, evt -> {
209             if (evt.getNewValue() instanceof Boolean) {
210                 // TODO FiltersLoading pas utiliser !
211                 getModel().getExtractionsTableUIModel().setFiltersLoading((Boolean) evt.getNewValue());
212             }
213         });
214 
215         // Change context value
216         getModel().addPropertyChangeListener(ExtractionUIModel.PROPERTY_CONTEXT, evt -> getContext().setSelectedContext(getModel().getContext()));
217 
218     }
219 
220     /**
221      * Methode permettant le changement des extractions.
222      *
223      * @param extractions La liste des observations
224      */
225     public void loadExtractions(final List<ExtractionDTO> extractions) {
226         getModel().getExtractionsTableUIModel().setBeans(extractions);
227 
228         // auto select unique row
229         if (getModel().getExtractionsTableUIModel().getRowCount() == 1) {
230             ExtractionsRowModel rowModel = getModel().getExtractionsTableUIModel().getRows().get(0);
231             SwingUtilities.invokeLater(() -> {
232                 getUI().getExtractionsTable().getHandler().selectRow(rowModel);
233                 getModel().getExtractionsTableUIModel().setSingleSelectedRow(rowModel);
234             });
235         }
236     }
237 
238     /**
239      * return a ordered set of PMFM available for the specified program list and periods
240      * need a Set instead of List (Mantis #44115)
241      *
242      * @param currentProgramCodes the program codes
243      * @param currentPeriods the periods
244      * @return a ordered set of PMFM
245      */
246     public Set<PmfmDTO> getPmfmsForSelectedExtraction(Collection<String> currentProgramCodes, Collection<ExtractionPeriodDTO> currentPeriods) {
247 
248         if (getModel().getSelectedExtraction() == null) return null;
249 
250         Collection<String> programCodes = currentProgramCodes != null
251                 ? currentProgramCodes
252                 : DaliBeans.getFilterElementsIds(getModel().getSelectedExtraction(), ExtractionFilterTypeValues.PROGRAM);
253         Collection<ExtractionPeriodDTO> extractionPeriods = currentPeriods != null
254                 ? currentPeriods
255                 : DaliBeans.getExtractionPeriods(getModel().getSelectedExtraction());
256         Set<PmfmStrategyDTO> pmfmStrategies = Sets.newHashSet();
257 
258         for (ExtractionPeriodDTO period : extractionPeriods) {
259             pmfmStrategies.addAll(getContext().getProgramStrategyService().getPmfmStrategiesByProgramsAndDates(programCodes, period.getStartDate(), period.getEndDate()));
260         }
261 
262         return pmfmStrategies.stream().filter(pmfmStrategy -> pmfmStrategy.isSampling() && pmfmStrategy.isGrouping())
263                 .sorted(Comparator.comparing(PmfmStrategyDTO::getRankOrder))
264                 .map(PmfmStrategyDTO::getPmfm).collect(Collectors.toCollection(LinkedHashSet::new));
265     }
266 
267     /** {@inheritDoc} */
268     @Override
269     public SwingValidator<ExtractionUIModel> getValidator() {
270         return getUI().getValidator();
271     }
272 
273     /** {@inheritDoc} */
274     @Override
275     @SuppressWarnings("unchecked")
276     public boolean quitUI() {
277         try {
278             QuitScreenAction action = new QuitScreenAction(this, false, SaveAction.class);
279             if (action.prepareAction()) {
280                 return true;
281             }
282         } catch (Exception e) {
283             LOG.error(e.getLocalizedMessage(), e);
284         }
285         return false;
286     }
287 }