/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2005 C.Marchand - christophe.marchand@axyus.com
 *
 * This file is part of XEMELIOS.
 *
 * XEMELIOS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * XEMELIOS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with XEMELIOS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package fr.gouv.finances.cp.xemelios.ui;

import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;

import org.apache.log4j.Logger;

import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

import fr.gouv.finances.cp.utils.ui.IhmFactory;
import fr.gouv.finances.cp.xemelios.common.config.ElementModel;
import fr.gouv.finances.cp.xemelios.common.config.RechercheModel;

/**
 * Cette boite de dialogue affiche la structure de
 * la base a l'utilisateur afin de lui permettre
 * de selectionner les branches a supprimer.
 * @author chm
 */
public class DlgSelectRequest extends JDialog {
    /**
     * Comment for <code>serialVersionUID</code>
     */
    private static final long serialVersionUID = 3256721779816151348L;
    private static final Logger logger = Logger.getLogger((DlgSelectRequest.class));
    private Action escapeAction;
    private Vector<? extends Object> data;
    private boolean ret = false;
    private JList list = null;
    private MainWindow parentFrame = null;
    private ElementModel elementModel = null;
    
    private static ImageIcon searchSaved, searchPlugin, exportPlugin/*, deleteIcon*/;
    static {
//        IhmFactory iF = IhmFactory.newInstance();
        exportPlugin = IhmFactory.getIconFromResource(ImageResources.LST_EXPORT_P);
        searchPlugin = IhmFactory.getIconFromResource(ImageResources.LST_SEARCH_P);
        searchSaved = IhmFactory.getIconFromResource(ImageResources.LST_SEARCH_SAV);
//        deleteIcon = iF.getIconFromResource(ImageResources.LST_DELETE_SEARCH);
    }
    
    public DlgSelectRequest(MainWindow parent,Vector<? extends ListDisplayable> data, ElementModel elementModel) {
        super(parent,true);
        this.data = data;
        this.parentFrame=parent;
        this.elementModel=elementModel;
        initComponents();
    }
    protected void initComponents() {
        int sepInfo = 2;						// 2
        int lineInfo = sepInfo + 2;				// 4
        int sepData = lineInfo + 2;				// 6
        int listLine = sepData + 2;				// 8
        int buttonLine1 = listLine + 2;			// 10
        
        JTextArea area = null;
        
        FormLayout fl = new FormLayout(
                //        1		2	  3	   4
                "3dlu,20dlu,160dlu,3dlu",
                "7dlu,"+                                   // 1
                "pref,"+                                   // 2
                "3dlu,"+                                   // 3
                "pref,"+                                   // 4
                "7dlu,"+                                   // 5
                "pref,"+                                   // 6
                "3dlu,"+                                   // 7
                "90dlu,"+                                  // 8
                "7dlu,"+                                   // 9
                "pref,"+                                   // 10
                "7dlu");                                   // 11
        CellConstraints cc = new CellConstraints();
        PanelBuilder pb = new PanelBuilder(fl);
//		IhmFactory iF=IhmFactory.newInstance();
        //final JTree tree = new JTree(new DatabaseTreeData(dm,wrapper));
        list = new JList(data);
        JButton pbCancel;
        
        pb.addSeparator("Informations",					cc.xyw(2,sepInfo,2));
        pb.add(area = new JTextArea(), 					cc.xy(3,lineInfo));
        
        pb.addSeparator("Recherches",					cc.xyw(2,sepData,2));
        pb.add(new JScrollPane(list),		cc.xy(3,listLine,"fill, fill"));
        
        final JButton pbOk = new JButton("Ok");
        
        JPanel bPane = new JPanel(new FlowLayout(FlowLayout.CENTER));
        bPane.add(pbOk);
        bPane.add(pbCancel = new JButton(escapeAction));
        
        pb.add(bPane,	cc.xyw(2,buttonLine1,2));
        
        area.setEditable(false);
        area.setLineWrap(true);
        area.setRows(3);
        area.setBackground(getBackground());
        area.setText("Sélectionnez dans la liste ci-dessous\n" +
                "la recherche que vous souhaitez réafficher.");
        
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        list.setCellRenderer(new MyCellRenderer());
        list.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent evt) {
                if(evt.getClickCount()==2 && evt.getButton()==MouseEvent.BUTTON1) {
                    pbOk.doClick();
                } else if(evt.getClickCount()==1 && (evt.getButton()==MouseEvent.BUTTON2||evt.getButton()==MouseEvent.BUTTON3)) {
//		        } else if(evt.isPopupTrigger()) {
                    Point clickPos = evt.getPoint();
                    int index = list.locationToIndex(clickPos);
                    final ListDisplayable ld = (ListDisplayable)list.getModel().getElementAt(index);
                    if(ld.isDeletable()) {
                        JPopupMenu pm = new JPopupMenu();
                        JMenuItem mnu = new JMenuItem("Supprimer cette requête");
                        mnu.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                                if(JOptionPane.showConfirmDialog(DlgSelectRequest.this,"Voulez-vous vraiment supprimer cette requête :\n"+ld.getDisplayName()+" ?")==JOptionPane.YES_OPTION) {
                                    logger.debug("suppression");
                                    RechercheModel rm = (RechercheModel)ld;
                                    parentFrame.getSavedRequest(elementModel).delete(rm);
                                    data.remove(rm);
                                    list.setListData(data);
                                }
                            }
                        });
                        pm.add(mnu);
                        pm.show(list,clickPos.x,clickPos.y);
                    }
                }
            }
        });
        getRootPane().setDefaultButton(pbCancel);
        
        setContentPane(pb.getPanel());
        
        pbOk.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                if(list.getSelectedValue()!=null) {
                    ret = true;
                    setVisible(false);
                }
            }
        });
        
        pack();
        setLocationRelativeTo(getParent());
    }
    
    public boolean run() {
        setVisible(true);
        return ret;
    }
    public Object getSelectedItem() {
        return list.getSelectedValue();
    }
    @Override
    protected JRootPane createRootPane() {
        KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0);
        JRootPane rp = new JRootPane();
        escapeAction = new AbstractAction("Annuler") {
            /**
             * Comment for <code>serialVersionUID</code>
             */
            private static final long serialVersionUID = 1L;
            
            public void actionPerformed(ActionEvent evt) {
                setVisible(false);
            }
        };
        rp.registerKeyboardAction(escapeAction,"TOTOTOTO",ks,JComponent.WHEN_IN_FOCUSED_WINDOW);
        return rp;
    }
    private class MyCellRenderer extends DefaultListCellRenderer {
        /**
         * Comment for <code>serialVersionUID</code>
         */
        private static final long serialVersionUID = 1L;
        public MyCellRenderer() {
            super();
            
        }
        @Override
        public Component getListCellRendererComponent(JList list,Object value,int index,boolean isSelected,boolean cellHasFocus) {
            JLabel ancestor = (JLabel)super.getListCellRendererComponent(list,value,index,isSelected,cellHasFocus);
            ListDisplayable ld = (ListDisplayable)value;
            ImageIcon ii=null;
            JLabel ret = null;
            if(ld.getResource()==null) {
                ret = new JLabel(ld.getDisplayName());
            } else if(ld.getResource().equals(ImageResources.LST_EXPORT_P)) ii=exportPlugin;
            else if(ld.getResource().equals(ImageResources.LST_SEARCH_P)) ii=searchPlugin;
            else if(ld.getResource().equals(ImageResources.LST_SEARCH_SAV)) ii=searchSaved;
            ret = new JLabel(ld.getDisplayName(),ii,JLabel.LEFT);
            
            ret.setBorder(ancestor.getBorder());
            ret.setBackground(ancestor.getBackground());
            ret.setForeground(ancestor.getForeground());
            
//	        BorderLayout bl = new BorderLayout();
//	        bl.setHgap(0); bl.setVgap(0);
//	        JPanel pane = new JPanel(bl);
//	        pane.setBackground(ancestor.getBackground());
//	        pane.add(ret,BorderLayout.CENTER);
            
//	        if(ld.isDeletable()) {
//	            JLabel delete = new JLabel(deleteIcon);
//	            delete.setToolTipText("Supprimer cette recherche");
//	            delete.addMouseListener(new MouseAdapter() {
//	                public void mouseClicked(MouseEvent e) {
//	                    logger.debug("delete clicked !");
//	                    if(e.getClickCount()==1) {
//	                        if(aValue instanceof RechercheModel) {
//	                            RechercheModel rm = (RechercheModel)aValue;
//	                            if(JOptionPane.showConfirmDialog(DlgSelectRequest.this,"Voulez-vous vraiment supprimer cette requête :\n"+rm.getName()+" ?")==JOptionPane.YES_OPTION) {
//	                                parentFrame.getSavedRequest(etatModel).delete(rm);
//	                            }
//	                        }
//	                    }
//	                }
//	            });
//	            pane.add(delete,BorderLayout.EAST);
//	        }
            return ret;
        }
        
        
    }
}
