001    
002    /*****************************************************************************
003     *
004     * jBudget.
005     * Copyright (C) 2006  Dmitri Petrov
006     *
007     * This program is free software: you can redistribute it and/or modify
008     * it under the terms of the GNU General Public License as published by
009     * the Free Software Foundation, either version 3 of the License, or
010     * (at your option) any later version.
011     *
012     * This program is distributed in the hope that it will be useful,
013     * but WITHOUT ANY WARRANTY; without even the implied warranty of
014     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
015     * GNU General Public License for more details.
016     *
017     * You should have received a copy of the GNU General Public License
018     * along with this program.  If not, see <http://www.gnu.org/licenses/>.
019     * 
020     ****************************************************************************/
021     
022    
023    /*
024     * TransactionFilterPanel.java
025     *
026     * Created on May 4, 2006, 7:53 AM
027     */
028    
029    package org.jbudget.gui.trans;
030    
031    import java.awt.Component;
032    import java.awt.Dimension;
033    import java.awt.event.ActionEvent;
034    import java.awt.event.ActionListener;
035    import java.awt.event.ItemEvent;
036    import java.awt.event.ItemListener;
037    import java.text.ParseException;
038    import java.util.ArrayList;
039    import java.util.Calendar;
040    import java.util.Collections;
041    import java.util.Date;
042    import java.util.GregorianCalendar;
043    import java.util.HashSet;
044    import java.util.List;
045    import java.util.Set;
046    import javax.swing.BorderFactory;
047    import javax.swing.DefaultListCellRenderer;
048    import javax.swing.JComboBox;
049    import javax.swing.JList;
050    import javax.swing.border.EtchedBorder;
051    import org.jbudget.Core.Budget;
052    import org.jbudget.Core.MoneyPit;
053    import org.jbudget.Core.Month;
054    import org.jbudget.gui.templ.TransactionFilterPanelTemplate;
055    import org.jbudget.io.DataManager;
056    import org.jbudget.Core.TransactionFilter;
057    import org.jbudget.gui.FilterChangeDispatcher;
058    import org.jbudget.gui.FilterChangeListener;
059    import org.jbudget.gui.MainWindow;
060    import org.jbudget.util.CurrencyFormater;
061    import org.jbudget.util.Pair;
062    
063    /**
064     * A class that creates a gui that allows configuration of the filter in
065     * the transaction list.
066     *
067     * @author petrov
068     */
069    public class TransactionFilterPanel extends TransactionFilterPanelTemplate
070                                        implements FilterChangeListener 
071    {
072        
073        //============================= Data ===================================//
074        
075        /** The filter instance that we are configuring */
076        private TransactionFilter filter;
077        
078        /** An instance of the Calendar class. */
079        private final Calendar calendar = new GregorianCalendar();
080        
081        /** Lists of variables synchronized to the appropriate GUI components */
082        private final List<MoneyPit> 
083                availableSources = new ArrayList<MoneyPit>();
084        
085        private List<MoneyPit> selectedSources = new ArrayList<MoneyPit>();
086        
087        private final List<MoneyPit> 
088                availableDestinations = new ArrayList<MoneyPit>();
089        
090        private List<MoneyPit> selectedDestinations = new ArrayList<MoneyPit>();
091        
092        /** A flag that is used to disable sending filter updates when the
093         * GUI is updated programmatically.*/
094        boolean signalingDisabled = false;
095        
096        //=======================================================================//
097        
098        /** Creates a new instance of TransactionFilterPanel */
099        public TransactionFilterPanel(TransactionFilter filter)
100        {
101            this.filter = filter;
102            
103            setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
104            
105            selectedSources.addAll(filter.getSources());
106            selectedDestinations.addAll(filter.getDestinations());
107            
108            availableSourcesList.setCellRenderer(new MyCellRenderer());
109            selectedSourcesList.setCellRenderer(new MyCellRenderer());
110            
111            availableDestList.setCellRenderer(new MyCellRenderer());
112            selectedDestList.setCellRenderer(new MyCellRenderer());
113            
114            setPreferredSize(new Dimension(450, 100));
115            
116            synchronizeGui();
117            initActions();
118            
119            FilterChangeDispatcher.getInstance().addListener(this);
120        }
121        
122        /** Updates the available and selected lists of sources and
123         * destinations based on the first and last date selected 
124         * in the filter. Only sources from the months between those 
125         * dates are included in the lists.
126         */
127        private void updateLists()
128        {
129            DataManager manager = DataManager.getInstance();
130            
131            // Get a set of selected months.
132            Set<Month> months = new HashSet<Month>();
133            
134            if (manager.isValidMonth(filter.startingDate))
135                months.add(manager.getMonth(filter.startingDate));
136            
137            calendar.setTime(filter.startingDate);
138            calendar.set(Calendar.DAY_OF_MONTH, 1);
139            calendar.add(Calendar.MONTH, 1);
140            Date currDate = calendar.getTime();
141            
142            while (currDate.before(filter.endingDate))
143            {
144                if(manager.isValidMonth(currDate))
145                    months.add(manager.getMonth(currDate));
146                
147                calendar.add(Calendar.MARCH, 1);
148                currDate = calendar.getTime();
149            }
150            
151            if (manager.isValidMonth(filter.endingDate))
152                months.add(manager.getMonth(filter.endingDate));
153            
154            // Get a set of budgets from selected months.
155            Set<Budget> budgets = new HashSet<Budget>();
156            
157            for (Month month : months)
158                budgets.add(month.getBudget());
159            
160            // Now update the lists of sources and destinations.
161            Set<MoneyPit> sources = new HashSet<MoneyPit>();
162            Set<MoneyPit> destinations = new HashSet<MoneyPit>();
163            
164            for (Budget budget : budgets)
165            {
166                sources.addAll(budget.getAllSources());
167                destinations.addAll(budget.getAllDestinations());
168            }
169            
170            availableSources.clear();
171            availableSources.addAll(sources);
172            
173            availableDestinations.clear();
174            availableDestinations.addAll(destinations);
175                
176            selectedSources.retainAll(sources);
177            selectedDestinations.retainAll(destinations);
178            
179            availableSources.removeAll(selectedSources);
180            availableDestinations.removeAll(selectedDestinations);
181        }
182        
183        /** Initializes actions for the gui components */
184        private void initActions()
185        {
186            strictCheckBox.addItemListener(new ItemListener()
187            {
188                public void itemStateChanged(ItemEvent ev)
189                {
190                    filter.requireDestAndSource =
191                        ev.getStateChange() == ItemEvent.SELECTED;
192                    signal();
193                }
194            });
195            
196            // Sources
197            sourceCheckBox.addItemListener(new ItemListener()
198            {
199                public void itemStateChanged(ItemEvent ev)
200                {
201                    filter.showAllSources = 
202                            ev.getStateChange() == ItemEvent.DESELECTED;
203                    
204                    strictCheckBox.setEnabled((!filter.showAllSources) &&
205                                              (!filter.showAllDestinations));
206                    signal();
207                }
208            });
209            
210            srcSubcatCheckBox.addItemListener(new ItemListener()
211            {
212                public void itemStateChanged(ItemEvent ev)
213                {
214                    filter.setInclSrcSubcat(
215                        ev.getStateChange() == ItemEvent.SELECTED
216                        );
217                    signal();
218                }
219            });
220            
221            addSourceButton.addActionListener(new ActionListener()
222            {
223                public void actionPerformed(ActionEvent ev)
224                {
225                    
226                    int [] indices = availableSourcesList.getSelectedIndices();
227                    for (int i = indices.length - 1 ; i >= 0 ; i--)
228                    {
229                        MoneyPit src = availableSources.remove(indices[i]);
230                        selectedSources.add(src);
231                        filter.addSource(src);
232                    }
233                    if (indices.length > 0)
234                    {
235                        Collections.sort(availableSources);
236                        Collections.sort(selectedSources);
237                        selectedSourcesList.setListData(selectedSources.toArray());
238                        availableSourcesList.setListData(availableSources.toArray());
239                    }
240                    
241                    int maxIndex = availableSources.size() - 1;
242                    if (indices.length > 0 && maxIndex >= 0)
243                    {
244                        int index = indices[indices.length -1];
245                        if (index > maxIndex)
246                            index = maxIndex;
247                        availableSourcesList.setSelectedIndex(index);
248                    }
249                    signal();
250                }
251            });
252            
253            removeSourceButton.addActionListener(new ActionListener()
254            {
255                public void actionPerformed(ActionEvent ev)
256                {
257                    
258                    int [] indices = selectedSourcesList.getSelectedIndices();
259                    for (int i = indices.length - 1 ; i >= 0 ; i--)
260                    {
261                        MoneyPit src = selectedSources.remove(indices[i]);
262                        availableSources.add(src);
263                        filter.removeSource(src);
264                    }
265                    if (indices.length > 0)
266                    {
267                        Collections.sort(availableSources);
268                        Collections.sort(selectedSources);
269                        selectedSourcesList.setListData(selectedSources.toArray());
270                        availableSourcesList.setListData(availableSources.toArray());
271                    }
272                    
273                    int maxIndex = selectedSources.size() - 1;
274                    if (indices.length > 0 && maxIndex >= 0)
275                    {
276                        int index = indices[indices.length -1];
277                        if (index > maxIndex)
278                            index = maxIndex;
279                        selectedSourcesList.setSelectedIndex(index);
280                    }
281                    signal();
282                }
283            });  
284            
285            // Destinations
286            destinationCheckBox.addItemListener(new ItemListener()
287            {
288                public void itemStateChanged(ItemEvent ev)
289                {
290                    filter.showAllDestinations =
291                                ev.getStateChange() == ItemEvent.DESELECTED;
292                    
293                    strictCheckBox.setEnabled((!filter.showAllSources) &&
294                                              (!filter.showAllDestinations));
295                    signal();
296                }
297            });
298            
299            destSubcatCheckBox.addItemListener(new ItemListener()
300            {
301                public void itemStateChanged(ItemEvent ev)
302                {
303                    filter.setInclDestSubcat(
304                        ev.getStateChange() == ItemEvent.SELECTED
305                        );
306                    signal();
307                }
308            });
309            
310            addDestButton.addActionListener(new ActionListener()
311            {
312                public void actionPerformed(ActionEvent ev)
313                {
314                    
315                    int [] indices = availableDestList.getSelectedIndices();
316                    for (int i = indices.length - 1 ; i >= 0 ; i--)
317                    {
318                        MoneyPit dest = availableDestinations.remove(indices[i]);
319                        selectedDestinations.add(dest);
320                        filter.addDestination(dest);
321                    }
322                    if (indices.length > 0)
323                    {
324                        Collections.sort(availableDestinations);
325                        Collections.sort(selectedDestinations);
326                        selectedDestList.setListData(selectedDestinations.toArray());
327                        availableDestList.setListData(availableDestinations.toArray());
328                    }
329                    
330                    int maxIndex = availableDestinations.size() - 1;
331                    if (indices.length > 0 && maxIndex >= 0)
332                    {
333                        int index = indices[indices.length -1];
334                        if (index > maxIndex)
335                            index = maxIndex;
336                        availableDestList.setSelectedIndex(index);
337                    }
338                    signal();
339                }
340            });
341            
342            removeDestButton.addActionListener(new ActionListener()
343            {
344                public void actionPerformed(ActionEvent ev)
345                {
346                    
347                    int [] indices = selectedDestList.getSelectedIndices();
348                    for (int i = indices.length - 1 ; i >= 0 ; i--)
349                    {
350                        MoneyPit dest = selectedDestinations.remove(indices[i]);
351                        availableDestinations.add(dest);
352                        filter.removeDest(dest);
353                    }
354                    if (indices.length > 0)
355                    {
356                        Collections.sort(availableDestinations);
357                        Collections.sort(selectedDestinations);
358                        selectedDestList.setListData(selectedDestinations.toArray());
359                        availableDestList.setListData(availableDestinations.toArray());
360                    }
361                    
362                    int maxIndex = selectedDestinations.size() - 1;
363                    if (indices.length > 0 && maxIndex >= 0)
364                    {
365                        int index = indices[indices.length -1];
366                        if (index > maxIndex)
367                            index = maxIndex;
368                        selectedDestList.setSelectedIndex(index);
369                    }
370                    signal();
371                }
372            });
373            
374            // Dates
375            firstDaySelector.addActionListener(new ActionListener()
376            {
377                public void actionPerformed(ActionEvent ev)
378                {
379                    Date prevDate = filter.startingDate;
380                    filter.startingDate = firstDaySelector.getDate();
381                    calendar.setTime(prevDate);
382                    int prevMonth = calendar.get(Calendar.MONTH);
383                    calendar.setTime(filter.startingDate);
384                    int currMonth = calendar.get(Calendar.MONTH);
385                    if (currMonth != prevMonth)
386                        updateLists();
387                    signal();
388                }
389            });
390            
391            lastDaySelector.addActionListener(new ActionListener()
392            {
393                public void actionPerformed(ActionEvent ev)
394                {
395                    Date prevDate = filter.endingDate;
396                    filter.endingDate = lastDaySelector.getDate();
397                    calendar.setTime(prevDate);
398                    int prevMonth = calendar.get(Calendar.MONTH);
399                    calendar.setTime(filter.endingDate);
400                    int currMonth = calendar.get(Calendar.MONTH);
401                    if (currMonth != prevMonth)
402                        updateLists();
403                    signal();
404                }
405            });
406            
407            // ID
408            
409            uidCheckBox.addItemListener(new ItemListener()
410            {
411                public void itemStateChanged(ItemEvent ev)
412                {
413                    filter.showAllUids = ev.getStateChange() == ItemEvent.DESELECTED;
414                    signal();
415                }
416            });
417            
418            uidComboBox.addItemListener(new ItemListener()
419            {
420                public void itemStateChanged(ItemEvent ev)
421                {
422                    JComboBox box = (JComboBox)ev.getSource();
423                    filter.validUids.clear();
424                    String selectedUser = (String)(uidComboBox.getSelectedItem());
425                    for (Pair<Integer,String> userInfo :
426                            DataManager.getInstance().getValidUsers())
427                    {
428                        if (userInfo.second().equals(selectedUser))
429                        {
430                            filter.validUids.add(userInfo.first());
431                            signal();
432                            return;
433                        }
434                    }
435                }
436            });
437            
438            // amounts
439            
440            amountCheckBox.addItemListener(new ItemListener()
441            {
442                public void itemStateChanged(ItemEvent ev)
443                {
444                    filter.filterAmounts = ev.getStateChange() == ItemEvent.SELECTED;
445                    signal();
446                }
447            });
448            
449            minAmountText.addActionListener(new ActionListener()
450            {
451                public void actionPerformed(ActionEvent ev)
452                {
453                    String amountStr = minAmountText.getText();
454                    try
455                    {
456                        filter.minAmount = CurrencyFormater.parse(amountStr);
457                        signal();
458                    }
459                    catch(ParseException ex)
460                    {}
461                    minAmountText.setText(CurrencyFormater.format(filter.minAmount));
462                }
463            });
464            
465            maxAmountText.addActionListener(new ActionListener()
466            {
467                public void actionPerformed(ActionEvent ev)
468                {
469                    String amountStr = maxAmountText.getText();
470                    try
471                    {
472                        filter.maxAmount = CurrencyFormater.parse(amountStr);
473                        signal();
474                    }
475                    catch(ParseException ex)
476                    {}
477                    maxAmountText.setText(CurrencyFormater.format(filter.maxAmount));
478                }
479            });
480            
481            // buttons
482            
483            currentMonthButton.addActionListener(new ActionListener()
484            {
485                public void actionPerformed(ActionEvent ev)
486                {
487                    setFilter(new TransactionFilter());
488                    signal();
489                }
490            });
491            
492            selectedMonthButton.addActionListener(new ActionListener()
493            {
494                public void actionPerformed(ActionEvent ev)
495                {
496                    TransactionFilter newFilter = new TransactionFilter();
497                    Month month = MainWindow.getLastInstance().getSelectedMonth();
498                    if (month == null)
499                        return;
500                    
501                    newFilter.startingDate = month.startingDate;
502                    newFilter.endingDate = month.endingDate;
503                    
504                    setFilter(newFilter);
505                    signal();
506                }
507            });
508        }
509        
510        /** Makes sure that the state of the GUI reflects the state of the
511         *  the filter object
512         */
513        public void synchronizeGui()
514        {
515            signalingDisabled = true;
516            
517            updateLists();
518            
519            // Synchronizing sources.
520            
521            strictCheckBox.setSelected(filter.requireDestAndSource);
522            strictCheckBox.setEnabled((!filter.showAllSources) &&
523                                      (!filter.showAllDestinations));
524            
525            sourceCheckBox.setSelected(!filter.showAllSources);
526            
527            srcSubcatCheckBox.setEnabled(!filter.showAllSources);
528            selectedSourcesList.setEnabled(!filter.showAllSources);
529            availableSourcesList.setEnabled(!filter.showAllSources);
530            addSourceButton.setEnabled(!filter.showAllSources);
531            removeSourceButton.setEnabled(!filter.showAllSources);
532            
533            srcSubcatCheckBox.setSelected(filter.getInclSrcSubcat());
534            
535            selectedSourcesList.setListData(selectedSources.toArray());
536            availableSourcesList.setListData(availableSources.toArray());
537            
538            // Synchronizing destinations.
539            destinationCheckBox.setSelected(!filter.showAllDestinations);
540            
541            destSubcatCheckBox.setEnabled(!filter.showAllDestinations);
542            selectedDestList.setEnabled(!filter.showAllDestinations);
543            availableDestList.setEnabled(!filter.showAllDestinations);
544            addDestButton.setEnabled(!filter.showAllDestinations);
545            removeDestButton.setEnabled(!filter.showAllDestinations);
546            
547            destSubcatCheckBox.setSelected(filter.getInclDestSubcat());
548            
549            selectedDestList.setListData(selectedDestinations.toArray());
550            availableDestList.setListData(availableDestinations.toArray());
551            
552            
553            // Synchronizing Dates
554            firstDaySelector.setDate(filter.startingDate);
555            lastDaySelector.setDate(filter.endingDate);
556            
557            //Synchronizing UIDs.
558            uidCheckBox.setSelected(!filter.showAllUids);
559            
560            ArrayList<Integer> validUids = new ArrayList(filter.validUids.size());
561            validUids.addAll(filter.validUids);
562            
563            uidComboBox.removeAllItems();
564            for (Pair<Integer,String> userData :
565                DataManager.getInstance().getValidUsers())
566            {
567                uidComboBox.addItem(userData.second());
568            }
569                
570            if (validUids.size() > 0)
571            {
572                int uid = validUids.get(0).intValue();
573                for (Pair<Integer,String> userData :
574                            DataManager.getInstance().getValidUsers())
575                {
576                    if (uid == userData.first().intValue())
577                    {
578                        uidComboBox.setSelectedItem(userData.second());
579                        break;
580                    }
581                }
582    
583            }
584    
585            uidLabel.setEnabled(!filter.showAllUids);
586            uidComboBox.setEnabled(!filter.showAllUids);
587    
588            //Synchronizing Amounts
589            amountCheckBox.setSelected(filter.filterAmounts);
590    
591            minAmountText.setText(CurrencyFormater.format(filter.minAmount));
592            maxAmountText.setText(CurrencyFormater.format(filter.maxAmount));
593    
594            minAmountLabel.setEnabled(filter.filterAmounts);
595            minAmountText.setEnabled(filter.filterAmounts);
596            maxAmountLabel.setEnabled(filter.filterAmounts);
597            maxAmountText.setEnabled(filter.filterAmounts);
598            
599            signalingDisabled = false;
600        }
601        
602        /** Changes the filter object associated with this gui */
603        public void setFilter(TransactionFilter filter)
604        {
605            this.filter = filter;
606            selectedSources.clear();
607            selectedSources.addAll(filter.getSources());
608            selectedDestinations.clear();
609            selectedDestinations.addAll(filter.getDestinations());
610            synchronizeGui();
611        }
612        
613        public TransactionFilter getFilter()
614        {
615            return filter;
616        }
617        
618        /** Called when a new filter is created by an external gui component. */
619        public void filterUpdated(TransactionFilter newFilter, Object initiator)
620        {
621            if (initiator == this)
622                return;
623            setFilter(newFilter);
624        }
625        
626        /** Signals throu the FilterChangeDispatcher that the filter was updated. */
627        private void signal()
628        {
629            if (signalingDisabled)
630                return;
631            FilterChangeDispatcher.getInstance().filterUpdated(getFilter(), this);
632        }
633        
634        //========================================================================//
635     
636        class MyCellRenderer extends DefaultListCellRenderer
637        {
638            @Override
639            public Component getListCellRendererComponent( JList list,
640                                                           Object value,
641                                                           int index,
642                                                           boolean isSelected,
643                                                           boolean cellHasFocus )
644            {
645                super.getListCellRendererComponent(list, value,
646                                                   index, isSelected, cellHasFocus);
647                
648                setText(((MoneyPit)value).getDecoratedName());
649                
650                return this;
651            }
652        }
653    }