001/**
002 * DisplayCasesTableMethod.java
003 * jCOLIBRI2 framework. 
004 * @author Juan A. Recio-Garc�a.
005 * GAIA - Group for Artificial Intelligence Applications
006 * http://gaia.fdi.ucm.es
007 * 25/10/2007
008 */
009package es.ucm.fdi.gaia.jcolibri.extensions.recommendation.navigationByProposing;
010
011import java.awt.BorderLayout;
012import java.awt.event.ActionEvent;
013import java.awt.event.ActionListener;
014import java.util.ArrayList;
015import java.util.Collection;
016import java.util.HashMap;
017import java.util.Iterator;
018import java.util.List;
019import java.util.Vector;
020
021import javax.swing.Box;
022import javax.swing.BoxLayout;
023import javax.swing.ButtonGroup;
024import javax.swing.JButton;
025import javax.swing.JCheckBox;
026import javax.swing.JDialog;
027import javax.swing.JOptionPane;
028import javax.swing.JPanel;
029import javax.swing.JRadioButton;
030import javax.swing.JScrollPane;
031import javax.swing.JTable;
032import javax.swing.event.TableModelEvent;
033import javax.swing.table.TableModel;
034
035import org.apache.logging.log4j.LogManager;
036
037import es.ucm.fdi.gaia.jcolibri.cbrcore.Attribute;
038import es.ucm.fdi.gaia.jcolibri.cbrcore.CBRCase;
039import es.ucm.fdi.gaia.jcolibri.cbrcore.CaseComponent;
040import es.ucm.fdi.gaia.jcolibri.extensions.recommendation.casesDisplay.UserChoice;
041import es.ucm.fdi.gaia.jcolibri.extensions.recommendation.casesDisplay.utils.RadioButtonEditor;
042import es.ucm.fdi.gaia.jcolibri.extensions.recommendation.casesDisplay.utils.RadioButtonTableRenderer;
043import es.ucm.fdi.gaia.jcolibri.extensions.recommendation.navigationByAsking.ObtainQueryWithAttributeQuestionMethod;
044import es.ucm.fdi.gaia.jcolibri.method.gui.utils.WindowUtils;
045import es.ucm.fdi.gaia.jcolibri.method.retrieve.FilterBasedRetrieval.predicates.Equal;
046import es.ucm.fdi.gaia.jcolibri.method.retrieve.FilterBasedRetrieval.predicates.FilterPredicate;
047import es.ucm.fdi.gaia.jcolibri.util.AttributeUtils;
048
049/**
050 * This method shows the cases in a table and also allows to show buttons with 
051 * critiques.
052 * <br>
053 * It is an extension of jcolibri.extensions.recommendation.casesDisplay.DisplayCasesTableMethod used
054 * in navigationByProposing recommenders.
055 * <br>
056 * This method enables and disables the critiques buttons depending on the values of the 
057 * available cases. (For example, it has no sense to show a "creaper" button if there are
058 * not cheaper cases).
059 * Usually, displayed cases are the same than working cases, but when using diversity 
060 * algorithms only three of the working cases are displayed.
061 * 
062 * @author Juan A. Recio-Garcia
063 * @author Developed at University College Cork (Ireland) in collaboration with Derek Bridge.
064 * @version 1.0
065 *
066 * @see CriticalUserChoice
067 * @see es.ucm.fdi.gaia.jcolibri.extensions.recommendation.casesDisplay.DisplayCasesTableMethod
068 */
069public class DisplayCasesTableWithCritiquesMethod
070{
071    private static JDialog dialog;
072    
073    private static ButtonGroup group;
074    private static int returnCode = UserChoice.QUIT;
075
076    private static Collection<CBRCase> displayedCases;
077    private static Collection<CritiqueOption> displayedCritiques;
078    private static Collection<CBRCase> _availableCases;
079    
080    private static List<CritiqueOption> userCritiques;
081    private static JTable table;
082    
083    private static HashMap<CritiqueOption,JButton> critiquesMap;
084    
085    private static CBRCase critiquedQuery;
086    
087    
088    /**
089     * This method shows the cases in a table and also allows to show buttons with 
090     * critiques.
091     * @param cases to be shown
092     * @param critiques to the cases (buttons are automatically generated from these critiques).
093     * @param availableCases are the current working cases. Critiques are enabled depending on these cases.
094     * @return a CriticalUserChoice object.
095     */
096    public static CriticalUserChoice displayCasesInTableWithCritiques(Collection<CBRCase> cases, Collection<CritiqueOption> critiques, Collection<CBRCase> availableCases )
097    {
098        displayedCases = cases;
099        displayedCritiques = critiques;
100        _availableCases = availableCases;
101        critiquesMap = new HashMap<CritiqueOption, JButton>();
102        
103        dialog = new JDialog();
104        dialog.setTitle(cases.size()+" Retrieved cases");
105        dialog.setModal(true);
106        
107
108        userCritiques = new ArrayList<>();
109        
110        Vector<Object> columnNames = extractColumnNames(cases.iterator().next());
111        
112
113        Vector<Object> rows = new Vector<Object>();
114        for(CBRCase c: cases)
115            rows.add(getAttributes(c));
116        
117        table = new JTable(rows, columnNames){
118
119            private static final long serialVersionUID = 1L;
120
121            public void tableChanged(TableModelEvent e) {
122                        super.tableChanged(e);
123                        repaint();
124              }
125        };
126        
127        table.getColumn("Select").setCellRenderer(
128                new RadioButtonTableRenderer());
129        table.getColumn("Select").setCellEditor(
130                new RadioButtonEditor(new JCheckBox()));
131        
132        group = new ButtonGroup();
133        TableModel tm = table.getModel();
134        for(int i=0; i<tm.getRowCount();i++)
135        {
136            JRadioButton rb = (JRadioButton) tm.getValueAt(i, 0);
137            group.add(rb);
138            DisplayCasesTableWithCritiquesMethod any = new DisplayCasesTableWithCritiquesMethod();
139            rb.addActionListener(any.new ItemRadioButtonListener(i));
140        }
141        
142        
143        JScrollPane scrollPane = new JScrollPane(table);
144        table.setFillsViewportHeight(true);
145        
146        JPanel mainPanel = new JPanel();
147        mainPanel.setLayout(new BorderLayout());
148        mainPanel.add(scrollPane,BorderLayout.CENTER);
149        
150        
151        JPanel actionsPanel = new JPanel();
152        actionsPanel.setLayout(new BoxLayout(actionsPanel,BoxLayout.X_AXIS));
153        
154        JButton ok = new JButton("Add to Basket");
155        ok.addActionListener(new ActionListener(){
156            public void actionPerformed(ActionEvent arg0)
157            {
158                if(table.getSelectedRow() == -1)
159                    JOptionPane.showMessageDialog(dialog, "You should choose one item", "Error", JOptionPane.ERROR_MESSAGE);
160                else
161                {
162                    returnCode = UserChoice.BUY;
163                    Iterator<CBRCase> iter = displayedCases.iterator();
164                    CBRCase _case = iter.next();
165                    for(int i=0; i<table.getSelectedRow(); i++)
166                         _case = iter.next();
167                    critiquedQuery = _case;
168                    dialog.setVisible(false);
169                }
170            } 
171        });
172        JButton quit = new JButton("Quit");
173        quit.addActionListener(new ActionListener(){
174            public void actionPerformed(ActionEvent arg0)
175            {
176                returnCode = UserChoice.QUIT;
177                dialog.setVisible(false);
178            } 
179        });
180
181        actionsPanel.add(Box.createHorizontalGlue());
182        actionsPanel.add(ok);
183        actionsPanel.add(quit);
184        actionsPanel.add(Box.createHorizontalGlue());
185        
186        JPanel critiquesPanel = new JPanel();
187        critiquesPanel.setLayout(new BoxLayout(critiquesPanel,BoxLayout.X_AXIS));
188        critiquesPanel.add(Box.createHorizontalGlue());
189        for(CritiqueOption critique: critiques)
190        {
191            JButton b = new JButton(critique.getLabel());
192            DisplayCasesTableWithCritiquesMethod any = new DisplayCasesTableWithCritiquesMethod();
193            b.addActionListener(any.new CritiqueButtonAction(critique));
194            critiquesMap.put(critique, b);
195            critiquesPanel.add(b);
196            critiquesPanel.add(Box.createHorizontalGlue());
197        }
198        critiquesPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Critiques"));
199        
200        
201        JPanel south = new JPanel();
202        south.setLayout(new BoxLayout(south, BoxLayout.Y_AXIS));
203        south.add(actionsPanel);
204        south.add(critiquesPanel);
205        mainPanel.add(south, BorderLayout.SOUTH);
206        
207        dialog.getContentPane().add(mainPanel);
208        dialog.setSize(800, 600);
209        WindowUtils.centerWindow(dialog);
210        
211        System.out.println("Available cases:");
212        for(CBRCase c: _availableCases)
213            System.out.println(c);
214        
215        dialog.setVisible(true);
216
217        
218        return new CriticalUserChoice(returnCode, userCritiques, critiquedQuery);
219    }
220    
221    /**
222     * Disable critiques buttons depending on the selected case (row)
223     * @param row of the table
224     */
225    private static void disableCritiques(int row)
226    {
227        Iterator<CBRCase> iter = displayedCases.iterator();
228        CBRCase _case = iter.next();
229        for(int i=0; i<row; i++)
230           _case = iter.next();
231        
232        for(CritiqueOption co : displayedCritiques)
233        {
234            FilterPredicate fp = co.getPredicate();
235            Attribute a = co.getAttribute();
236            Object valueSelected = AttributeUtils.findValue(a, _case.getDescription());
237            boolean therearemore = false;
238            for(CBRCase cbCase : _availableCases)
239            {
240                Object valueOther    = AttributeUtils.findValue(a, cbCase);
241                try
242                {
243                    boolean res = fp.compute(valueOther,valueSelected);
244                    if(fp instanceof Equal)
245                        res = !res;
246                    if(res)
247                    {
248                        therearemore = true;
249                        break;
250                    }
251                } catch (Exception e)
252                {
253                    LogManager.getLogger(DisplayCasesTableWithCritiquesMethod.class).error(e);
254                    
255                }
256            }
257            critiquesMap.get(co).setEnabled(therearemore);
258        }
259        
260    }
261    
262    /**
263     * Returns the attributes of a case
264     */
265    private static Vector<Object> getAttributes(CBRCase c)
266    {
267        Vector<Object> res = new Vector<Object>();
268        
269        JRadioButton rb = new JRadioButton(c.getID().toString());
270        res.add(rb);
271        
272        getAttributes(c.getDescription(), res);
273        getAttributes(c.getSolution(), res);
274        getAttributes(c.getJustificationOfSolution(), res);
275        getAttributes(c.getResult(), res);
276        
277        return res;
278    }
279    
280    /**
281     * Returns the attributes of a CaseComponent
282     */
283    private static void getAttributes(CaseComponent cc, Vector<Object> res)
284    {
285        Collection<Attribute> atts = AttributeUtils.getAttributes(cc);
286        if(atts == null)
287            return;
288
289        Attribute id = cc.getIdAttribute();
290        for(Attribute a: atts)
291        {
292            if(!a.equals(id))
293                res.add(AttributeUtils.findValue(a, cc));
294        }
295    }
296    
297    /**
298     * Gets the column names from the names of the attributes of a case
299     */
300    private static Vector<Object> extractColumnNames(CBRCase c)
301    {
302        Vector<Object> res = new Vector<Object>();
303        res.add("Select");
304        extractColumnNames(c.getDescription(),res);
305        extractColumnNames(c.getSolution(),res);
306        extractColumnNames(c.getJustificationOfSolution(),res);
307        extractColumnNames(c.getResult(),res);
308        return res;
309    }
310    
311    /**
312     * Returns the names of the attributes of a CaseComponent.
313     */
314    private static void extractColumnNames(CaseComponent cc, Vector<Object> res)
315    {
316        Collection<Attribute> atts = AttributeUtils.getAttributes(cc);
317        if(atts == null)
318            return;
319        Attribute id = cc.getIdAttribute();
320        for(Attribute a: atts)
321        {
322            if(!a.equals(id))
323                res.add(a.getName());
324        }
325    }
326    
327    /**
328     * Listener for the RadioButtons
329     * @author Juan A. Recio-Garcia
330     * @version 1.0
331     */
332    private class ItemRadioButtonListener implements ActionListener
333    {
334        int row = 0;
335        public ItemRadioButtonListener(int row)
336        {
337            this.row = row;
338        }
339        public void actionPerformed(ActionEvent arg0)
340        {
341           JRadioButton rb = (JRadioButton)arg0.getSource();
342           if(rb.isSelected())
343               disableCritiques(row);
344        }
345        
346    }
347    
348    /**
349     * Listener for the critiques buttons.
350     * @author Juan A. Recio-Garcia
351     * @version 1.0
352     *
353     */
354    private class CritiqueButtonAction implements ActionListener
355    {
356        CritiqueOption critique;
357        public CritiqueButtonAction(CritiqueOption co)
358        {
359            critique = co;
360        }
361        public void actionPerformed(ActionEvent arg0)
362        {
363            if(table.getSelectedRowCount()<=0)
364            {
365                JOptionPane.showMessageDialog(dialog, "You should choose one item", "Error", JOptionPane.ERROR_MESSAGE);
366                return;
367            }
368
369            
370            Iterator<CBRCase> iter = displayedCases.iterator();
371            CBRCase _case = iter.next();
372            for(int i=0; i<table.getSelectedRow(); i++)
373                 _case = iter.next();
374            
375            critiquedQuery = _case;
376            returnCode = UserChoice.REFINE_QUERY;
377        
378            if(critique.getPredicate().getClass().equals(Equal.class))
379            {
380                ObtainQueryWithAttributeQuestionMethod.obtainQueryWithAttributeQuestion(critiquedQuery, critique.getAttribute(), new HashMap<Attribute,String>(), _availableCases);
381            }
382            userCritiques.add(critique);
383            dialog.setVisible(false);
384
385        }
386        
387    }
388    
389}