/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2009 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.dgfip.xemelios.auth.impl.std.db.ui;

import fr.gouv.finances.dgfip.xemelios.auth.impl.std.db.DataHelper;
import fr.gouv.finances.dgfip.utils.Pair;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.List;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.AbstractListModel;
import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 *
 * @author chm
 */
public class DlgProfilsUtilisateur extends javax.swing.JDialog {
    private DataHelper.StdUser user;
    private PairListModel profilsUserModel;
    private PairListModel profilsModel;

    /** Creates new form DlgProfilsUtilisateur */
    public DlgProfilsUtilisateur(java.awt.Dialog parent, DataHelper.StdUser user) {
        super(parent, "Profils", true);
        this.user=user;
        List<Pair> userProfiles = user.getProfils();
        List<Pair> profils = DataHelper.getProfilsAsPair();
        for(Pair p:userProfiles) profils.remove(p);
        profilsUserModel = new PairListModel(userProfiles);
        profilsModel = new PairListModel(profils);
        initComponents();
        profilsUserModel.setList(lstProfilsUser);
        profilsModel.setList(lstProfils);
        lstProfilsUser.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                JList lst = (JList)e.getSource();
                boolean selected = lst.getSelectedIndices().length>0;
                pbRemoveOne.setEnabled(selected);
            }
        });
        lstProfils.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                JList lst = (JList)e.getSource();
                boolean selected = lst.getSelectedIndices().length>0;
                pbAddOne.setEnabled(selected);
            }
        });
        setLocationRelativeTo(parent);
    }
    public void run() {
        setVisible(true);
    }
    protected JRootPane createRootPane() {
        KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0);
        JRootPane rp = new JRootPane();
        AbstractAction escapeAction = new AbstractAction("Annuler") {
            /**
             * Comment for <code>serialVersionUID</code>
             */
            private static final long serialVersionUID = 1L;

            public void actionPerformed(ActionEvent evt) {
                pbCancelActionPerformed(evt);
            }
        };
        rp.registerKeyboardAction(escapeAction,"TOTOTOTO",ks,JComponent.WHEN_IN_FOCUSED_WINDOW);
        return rp;
    }

    /** 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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblHeader = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        lstProfilsUser = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        lstProfils = new javax.swing.JList();
        pbOk = new javax.swing.JButton();
        pbCancel = new javax.swing.JButton();
        pbAddAll = new javax.swing.JButton();
        pbAddOne = new javax.swing.JButton();
        pbRemoveOne = new javax.swing.JButton();
        pbRemoveAll = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        lblHeader.setText("Profils de "+user.toString());

        lstProfilsUser.setModel(profilsUserModel);
        jScrollPane1.setViewportView(lstProfilsUser);

        lstProfils.setModel(profilsModel);
        jScrollPane2.setViewportView(lstProfils);

        pbOk.setText("Ok");
        pbOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pbOkActionPerformed(evt);
            }
        });

        pbCancel.setText("Annuler");
        pbCancel.setToolTipText("");
        pbCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pbCancelActionPerformed(evt);
            }
        });

        pbAddAll.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fr/gouv/finances/cp/xemelios/ui/resources/addAll.png"))); // NOI18N
        pbAddAll.setToolTipText("Tout ajouter");
        pbAddAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pbAddAllActionPerformed(evt);
            }
        });

        pbAddOne.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fr/gouv/finances/cp/xemelios/ui/resources/addOne.png"))); // NOI18N
        pbAddOne.setToolTipText("Ajouter");
        pbAddOne.setEnabled(false);
        pbAddOne.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pbAddOneActionPerformed(evt);
            }
        });

        pbRemoveOne.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fr/gouv/finances/cp/xemelios/ui/resources/removeOne.png"))); // NOI18N
        pbRemoveOne.setToolTipText("Supprimer");
        pbRemoveOne.setEnabled(false);
        pbRemoveOne.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pbRemoveOneActionPerformed(evt);
            }
        });

        pbRemoveAll.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fr/gouv/finances/cp/xemelios/ui/resources/removeAll.png"))); // NOI18N
        pbRemoveAll.setToolTipText("Tout supprimer");
        pbRemoveAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pbRemoveAllActionPerformed(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(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(lblHeader)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(pbCancel)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(pbOk))
                    .add(layout.createSequentialGroup()
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 145, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                                    .add(org.jdesktop.layout.GroupLayout.LEADING, pbAddOne, 0, 0, Short.MAX_VALUE)
                                    .add(org.jdesktop.layout.GroupLayout.LEADING, pbAddAll, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 22, Short.MAX_VALUE)))
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                                .add(org.jdesktop.layout.GroupLayout.TRAILING, pbRemoveAll, 0, 0, Short.MAX_VALUE)
                                .add(org.jdesktop.layout.GroupLayout.TRAILING, pbRemoveOne, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 22, Short.MAX_VALUE)))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 156, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(lblHeader)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(pbAddAll)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(pbAddOne)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(pbRemoveOne)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(pbRemoveAll))
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 217, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 19, Short.MAX_VALUE)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(pbOk)
                            .add(pbCancel))))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void pbCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbCancelActionPerformed
        user.setProfils(null);
        setVisible(false);
    }//GEN-LAST:event_pbCancelActionPerformed

    private void pbOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbOkActionPerformed
        DataHelper.saveUserProfils(user);
        setVisible(false);
    }//GEN-LAST:event_pbOkActionPerformed

    private void pbAddOneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbAddOneActionPerformed
        int[] indices = lstProfils.getSelectedIndices();
        Vector<Pair> toRemove = new Vector<Pair>();
        for(int pos:indices) {
            Pair p = (Pair)profilsModel.getElementAt(pos);
            profilsUserModel.addPair(p);
            toRemove.add(p);
        }
        for(Pair p:toRemove) profilsModel.removePair(p);
    }//GEN-LAST:event_pbAddOneActionPerformed

    private void pbAddAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbAddAllActionPerformed
        while(profilsModel.getSize()>0) {
            Pair p = (Pair)profilsModel.getElementAt(0);
            profilsUserModel.addPair(p);
            profilsModel.removePair(p);
        }
    }//GEN-LAST:event_pbAddAllActionPerformed

    private void pbRemoveOneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbRemoveOneActionPerformed
        int[] indices = lstProfilsUser.getSelectedIndices();
        Vector<Pair> toRemove = new Vector<Pair>();
        for(int pos:indices) {
            Pair p = (Pair)profilsUserModel.getElementAt(pos);
            profilsModel.addPair(p);
            toRemove.add(p);
        }
        for(Pair p:toRemove) profilsUserModel.removePair(p);
    }//GEN-LAST:event_pbRemoveOneActionPerformed

    private void pbRemoveAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbRemoveAllActionPerformed
        while(profilsUserModel.getSize()>0) {
            Pair p = (Pair)profilsUserModel.getElementAt(0);
            profilsModel.addPair(p);
            profilsUserModel.removePair(p);
        }
    }//GEN-LAST:event_pbRemoveAllActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblHeader;
    private javax.swing.JList lstProfils;
    private javax.swing.JList lstProfilsUser;
    private javax.swing.JButton pbAddAll;
    private javax.swing.JButton pbAddOne;
    private javax.swing.JButton pbCancel;
    private javax.swing.JButton pbOk;
    private javax.swing.JButton pbRemoveAll;
    private javax.swing.JButton pbRemoveOne;
    // End of variables declaration//GEN-END:variables

    static class PairListModel extends AbstractListModel {
        private List<Pair> data;
        private JList list;
        public PairListModel(List<Pair> data) {
            super();
            this.data=data;
        }
        public void setList(JList list) {
            this.list=list;
        }
        public Object getElementAt(int index) {
            return data.get(index);
        }

        public void addPair(Pair p) {
            data.add(p);
            fireIntervalAdded(list, data.size()-1, data.size()-1);
        }
        public Pair removePair(Pair p) {
            int pos = data.indexOf(p);
            if(pos>=0) {
                data.remove(pos);
                fireIntervalRemoved(list, pos, pos);
            }
            return p;
        }
        public int getSize() {
            return data.size();
        }
        public List<Pair> getData() { return data; }
    }
}
