/*
 * 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.controls;

import java.awt.Color;
import java.awt.Component;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.swing.JCheckBox;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.ListCellRenderer;
import javax.swing.ListSelectionModel;
import javax.swing.border.LineBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import fr.gouv.finances.cp.utils.Pair;
import fr.gouv.finances.cp.xemelios.controls.models.OptionModel;
import fr.gouv.finances.cp.xemelios.controls.models.ParamModel;

/**
 *
 * @author  chm
 */
public class DlgEditParam extends javax.swing.JDialog {
    public static final String SEPARATOR=" ";
    private ParamModel pm;
    
    /** Creates new form DlgEditParam */
    public DlgEditParam(java.awt.Frame parent, ParamModel pm) {
        super(parent, true);
        this.pm = pm;
        initAll();
    }
    public DlgEditParam(java.awt.Dialog parent, ParamModel pm) {
        super(parent, true);
        this.pm = pm;
        initAll();
    }
    private void initAll() {
        initComponents();
        setLocationRelativeTo(getParent());
        if(!pm.getSelect().isMultiValued()) {
            Vector<Pair> v = new Vector<Pair>();
            for(OptionModel om:pm.getSelect().getOptions()) {
                Pair p = new Pair(om.getValue(),om.getLibelle());
                v.add(p);
            }
            lst.setListData(v);
            pbAdd.setEnabled(true);
            lst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            lst.addListSelectionListener(new ListSelectionListener() {
                public void valueChanged(ListSelectionEvent e) {
                    pbRemove.setEnabled(lst.getSelectedIndex()>=0);
                }
            });
        } else {
            Object oValue = pm.getValue();
            HashSet<String> values = new HashSet<String>();
            if(oValue!=null && oValue instanceof String) {
                String s = (String)oValue;
                StringTokenizer tokenizer = new StringTokenizer(s,SEPARATOR);
                while(tokenizer.hasMoreTokens()) values.add(tokenizer.nextToken());
            }
            lst.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
            lst.setCellRenderer(new MyCellRenderer());
            Vector<String> data = new Vector<String>();
            Vector<Integer> selectedIndices = new Vector<Integer>();
            for(OptionModel om:pm.getSelect().getOptions()) {
                String key = om.getValue();
                if(values.contains(key)) selectedIndices.add(new Integer(data.size()));
                data.add(key);
            }
            lst.setListData(data);
            int[] indices = new int[selectedIndices.size()];
            for(int i=0;i<indices.length;i++) indices[i]=selectedIndices.get(i).intValue();
            lst.setSelectedIndices(indices);
            if(pm.getSelect().isEditable()) {
                pbAdd.setEnabled(true);
                lst.addListSelectionListener(new ListSelectionListener() {
                    public void valueChanged(ListSelectionEvent e) {
                        pbRemove.setEnabled(lst.getSelectedIndex()>=0);
                    }
                });
            }
        }
    }
    
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jScrollPane1 = new javax.swing.JScrollPane();
        lst = new javax.swing.JList();
        pbClose = new javax.swing.JButton();
        pbAdd = new javax.swing.JButton();
        pbRemove = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(pm.getName());
        lst.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        lst.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(lst);

        pbClose.setText("Fermer");
        pbClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pbCloseActionPerformed(evt);
            }
        });

        pbAdd.setText("Ajouter");
        pbAdd.setEnabled(false);
        pbAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pbAddActionPerformed(evt);
            }
        });

        pbRemove.setText("Supprimer");
        pbRemove.setEnabled(false);
        pbRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pbRemoveActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(pbRemove)
                    .add(pbAdd, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 98, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(pbClose, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 98, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(pbAdd)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(pbRemove)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 195, Short.MAX_VALUE)
                        .add(pbClose))
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 276, Short.MAX_VALUE))
                .addContainerGap())
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void pbAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbAddActionPerformed
        String s = JOptionPane.showInputDialog(this,"Valeur à ajouter :");
        OptionModel om = new OptionModel(s,s);
        try { pm.getSelect().addChild(om,OptionModel.QN); } catch(Throwable t) {}
        if(!pm.getSelect().isMultiValued()) {
            Vector<Pair> v = new Vector<Pair>();
            for(OptionModel om2:pm.getSelect().getOptions()) {
                Pair p = new Pair(om2.getValue(),om2.getLibelle());
                v.add(p);
            }
            lst.setListData(v);
        } else {
            Vector<String> data = new Vector<String>();
            for(OptionModel om2:pm.getSelect().getOptions()) {
                String key = om2.getValue();
                data.add(key);
            }
            lst.setListData(data);
        }
    }//GEN-LAST:event_pbAddActionPerformed

    private void pbRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbRemoveActionPerformed
        if(pm.getSelect().isEditable()) {
            if(!pm.getSelect().isMultiValued()) {
                Pair p = (Pair)lst.getSelectedValue();
                if(p!=null) {
                    int index = lst.getSelectedIndex();
                    lst.remove(index);
                    pm.getSelect().getOptions().remove(index);
                }
            } else {
                Object[] values = lst.getSelectedValues();
                Vector<String> v = new Vector<String>();
                for(Object value:values) v.add((String)value);
                Vector<OptionModel> toDrop = new Vector<OptionModel>();
                for(OptionModel om:pm.getSelect().getOptions()) {
                    if(v.contains(om.getValue())) toDrop.add(om);
                }
                pm.getSelect().getOptions().removeAll(toDrop);
                pm.setValue("");
                Vector<String> data = new Vector<String>();
                for(OptionModel om:pm.getSelect().getOptions()) {
                    String key = om.getValue();
                    data.add(key);
                }
                lst.setListData(data);
            }
        }
    }//GEN-LAST:event_pbRemoveActionPerformed

    private void pbCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbCloseActionPerformed
        if(pm.getSelect().isMultiValued()) {
            StringBuffer sb = new StringBuffer();
            int[] indices = lst.getSelectedIndices();
            for(int i:indices) {
                String s = lst.getModel().getElementAt(i).toString();
                sb.append(s).append(SEPARATOR);
            }
            if(sb.length()>1) sb.deleteCharAt(sb.length()-1);
            pm.setValue(sb.toString());
        }
        setVisible(false);
    }//GEN-LAST:event_pbCloseActionPerformed
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JList lst;
    private javax.swing.JButton pbAdd;
    private javax.swing.JButton pbClose;
    private javax.swing.JButton pbRemove;
    // End of variables declaration//GEN-END:variables
    
    private class MyCellRenderer extends JCheckBox implements ListCellRenderer {
        public MyCellRenderer() {
            super();
            setBorder(new LineBorder(Color.GRAY,1));
        }
        public Component getListCellRendererComponent(JList list,Object value,int index,boolean isSelected,boolean cellHasFocus) {
            if(value!=null) {
                setText(value.toString());
            } else {
                setText("");
            }
            setSelected(isSelected);
            setBorderPainted(cellHasFocus);
            if(cellHasFocus) {
                setBackground(list.getSelectionBackground());
                setForeground(list.getSelectionForeground());
            } else {
                setBackground(list.getBackground());
                setForeground(list.getForeground());
            }
            return this;
        }
    }
}
