001    /*****************************************************************************
002    
003        jBudget.
004        Copyright (C) 2008  Dmitri Petrov
005    
006        This program is free software: you can redistribute it and/or modify
007        it under the terms of the GNU General Public License as published by
008        the Free Software Foundation, either version 3 of the License, or
009        (at your option) any later version.
010    
011        This program is distributed in the hope that it will be useful,
012        but WITHOUT ANY WARRANTY; without even the implied warranty of
013        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
014        GNU General Public License for more details.
015    
016        You should have received a copy of the GNU General Public License
017        along with this program.  If not, see <http://www.gnu.org/licenses/>.
018     
019    *****************************************************************************/
020    
021    package org.jbudget.gui.month;
022    
023    import java.util.ArrayList;
024    import java.util.Collections;
025    import java.util.Comparator;
026    import java.util.List;
027    import org.jbudget.Core.Account;
028    import org.jbudget.Core.Budget;
029    import org.jbudget.Core.ExpenseCategory;
030    import org.jbudget.Core.MoneyPit;
031    import org.jdom.Attribute;
032    import org.jdom.Element;
033    import org.jdom.JDOMException;
034    
035    /**
036     *
037     * @author petrov
038     */
039    public class DefaultTableColumnSorter extends TableColumnSorter
040    {
041        // A pointer to the budget that is used for caching.
042        private Budget cachedBudget = null;
043        
044        // Sorted list of money pits from the budget.
045        private List<MoneyPit> sortedPits = null;
046        
047        public int getInsertionPoint(MoneyPit item, List<MoneyPit> otherItems)
048        {
049            // First we need to figure out what budget we should use.
050            Budget newBudget = null;
051            for (MoneyPit pit : otherItems)
052            {
053                if(pit.getType() == MoneyPit.Type.EXPENSE ||
054                   pit.getType() == MoneyPit.Type.INCOME)
055                {
056                    newBudget = pit.getBudget();
057                    break;  
058                }
059            }
060            
061            // Use default sorting.
062            if (newBudget == null)
063            {
064                Collections.sort(otherItems);
065                int index = Collections.binarySearch(otherItems, item);
066                if (index < 0)
067                    index = -(index + 1);
068                return index;
069            }
070            
071            updateList(newBudget);
072            Comparator<MoneyPit> comparator = new DefaultComparator(sortedPits);
073            Collections.sort(otherItems, comparator);
074            int index = Collections.binarySearch(otherItems, item, comparator);
075            if (index < 0)
076                index = -(index + 1);
077            return index;
078        }
079        
080        private void updateList(Budget newBudget)
081        {
082            if (newBudget.equals(cachedBudget))
083                return;
084            
085            List<MoneyPit> newPits = new ArrayList<MoneyPit>();
086            
087            // Start by adding and sorting all accounts.
088            for (Account account : newBudget.getRegisteredAccounts())
089                newPits.add(new MoneyPit(account));
090            
091            // Sort using the default sorting.
092            Collections.sort(newPits);
093            
094            // Now add the expense categories preserving the structure 
095            for (ExpenseCategory category : newBudget.getAllExpenseCategoriesSorted())
096                newPits.add(new MoneyPit(category, newBudget));
097            
098            cachedBudget = newBudget;
099            sortedPits = newPits;
100        }
101        
102        //=========================== XML Encoding ===============================//
103        
104        /** Returns the XML Element representing the 
105         * <code>DefaultTableColumnSorter</code>. */
106        public Element getXmlElement()
107        {
108           Element element = new Element(xmlNodeName);
109           element.setAttribute("variant", "Default");
110           
111           return element;
112        }
113        
114        
115        /** Creates a new DefaultTableColumnSorter instance using the information
116         * provided in a given JDOM Element.
117         * @throws JDOMException if there are parsing errors or the element does
118         *         not contain all necessary information.
119         */
120        public static DefaultTableColumnSorter getInstance (Element element)
121                                                                throws JDOMException
122        {
123            if (!xmlNodeName.equals(element.getName()))
124              throw new JDOMException ("Incorrect element. " + 
125                      "Expeced TableColumnSorter element. Got" +
126                      " " + element.getName() + " element");
127    
128            Attribute attr = element.getAttribute("variant");
129            if (attr == null)
130                throw new JDOMException("No TableColumnSorter variant specified");
131            String variant = attr.getValue();
132            
133            if (!variant.equalsIgnoreCase("Default"))
134            {
135                throw new JDOMException ("Incorrect element type. " + 
136                      "Expeced 'Default', got" + variant + " element");
137            }
138                
139            return new DefaultTableColumnSorter();
140        }
141        
142        //============================ Inner Classes ============================//
143        
144        static class DefaultComparator implements Comparator<MoneyPit>
145        {
146            List<MoneyPit> sortedPits;
147            
148            DefaultComparator(List<MoneyPit>sortedPits)
149            {
150                this.sortedPits = sortedPits;
151            }
152            
153            public int compare(MoneyPit o1, MoneyPit o2)
154            {
155                int index1 = sortedPits.indexOf(o1);
156                if (index1 < 0)
157                    return -1;
158                
159                int index2 = sortedPits.indexOf(o2);
160                if (index2 < 0)
161                    return 1;
162                return index1 - index2;
163            }   
164        }
165    }