/*
 * Copyright
 *   2009 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 General Public License as published by
 * the Free Software Foundation; either version 2 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 General Public License for more details.
 *
 * You should have received a copy of the GNU 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.utils.Pair;
import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
import fr.gouv.finances.dgfip.xemelios.auth.impl.std.db.StdDbAuthEngineImpl;
import java.util.ArrayList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import fr.gouv.finances.dgfip.xemelios.auth.impl.std.db.ui.DataHelper.Profil;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.util.TreeSet;
import javax.swing.AbstractListModel;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;

/**
 *
 * @author chm
 */
public class PnlProfils extends javax.swing.JPanel {
    private ArrayList<Profil> profils;
    private ProfilListModel lm;
    private DlgAdmin dlgAdmin;

    /** Creates new form PnlProfils */
    public PnlProfils(DlgAdmin dlgAdmin, ArrayList<Profil> profils) {
        super();
        this.dlgAdmin=dlgAdmin;
        this.profils = profils;
        lm = new ProfilListModel(profils);
        initComponents();
        lstProfils.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                boolean hasSelected = lstProfils.getSelectedIndex() >= -1;
                chkConnect.setEnabled(hasSelected);
                chkDelete.setEnabled(hasSelected);
                chkExport.setEnabled(hasSelected);
                chkImport.setEnabled(hasSelected);
                chkNavigate.setEnabled(hasSelected);
                chkSearch.setEnabled(hasSelected);
                chkAdminUser.setEnabled(hasSelected);
                if(hasSelected) {
                    Profil p = (Profil)lstProfils.getSelectedValue();
                    if(p!=null) {
                        chkConnect.setSelected(p.getFonctionnalites().contains(XemeliosUser.ROLE_CONNECT));
                        chkDelete.setSelected(p.getFonctionnalites().contains(XemeliosUser.ROLE_CLEAN));
                        chkExport.setSelected(p.getFonctionnalites().contains(XemeliosUser.ROLE_EXPORT));
                        chkImport.setSelected(p.getFonctionnalites().contains(XemeliosUser.ROLE_IMPORT));
                        chkNavigate.setSelected(p.getFonctionnalites().contains(XemeliosUser.ROLE_BROWSE));
                        chkSearch.setSelected(p.getFonctionnalites().contains(XemeliosUser.ROLE_SEARCH));
                        chkAdminUser.setSelected(p.getFonctionnalites().contains(StdDbAuthEngineImpl.ROLE_ADMIN));
                    } else {
                        chkConnect.setEnabled(false);
                        chkDelete.setEnabled(false);
                        chkExport.setEnabled(false);
                        chkImport.setEnabled(false);
                        chkNavigate.setEnabled(false);
                        chkSearch.setEnabled(false);
                        chkAdminUser.setEnabled(false);
                    }
                } else {
                    pbRemoveProfil.setEnabled(false);
                }
                pbRemoveProfil.setEnabled(hasSelected);
            }
        });
        chkAdminUser.addActionListener(new ChkActionListener(StdDbAuthEngineImpl.ROLE_ADMIN));
        chkConnect.addActionListener(new ChkActionListener(XemeliosUser.ROLE_CONNECT));
        chkDelete.addActionListener(new ChkActionListener(XemeliosUser.ROLE_CLEAN));
        chkExport.addActionListener(new ChkActionListener(XemeliosUser.ROLE_EXPORT));
        chkImport.addActionListener(new ChkActionListener(XemeliosUser.ROLE_IMPORT));
        chkNavigate.addActionListener(new ChkActionListener(XemeliosUser.ROLE_BROWSE));
        chkSearch.addActionListener(new ChkActionListener(XemeliosUser.ROLE_SEARCH));
    }

    /** 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() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        lstProfils = new javax.swing.JList(lm);
        pbAddProfil = new javax.swing.JButton();
        pbRemoveProfil = new javax.swing.JButton();
        chkConnect = new javax.swing.JCheckBox();
        chkImport = new javax.swing.JCheckBox();
        chkDelete = new javax.swing.JCheckBox();
        chkSearch = new javax.swing.JCheckBox();
        chkNavigate = new javax.swing.JCheckBox();
        chkExport = new javax.swing.JCheckBox();
        chkAdminUser = new javax.swing.JCheckBox();

        jLabel1.setText("Profils");

        lstProfils.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(lstProfils);

        pbAddProfil.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fr/gouv/finances/cp/xemelios/ui/resources/add.png"))); // NOI18N
        pbAddProfil.setToolTipText("Nouveau profil...");
        pbAddProfil.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pbAddProfilActionPerformed(evt);
            }
        });

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

        chkConnect.setText("Connection");
        chkConnect.setEnabled(false);
        chkConnect.setName("chkConnect"); // NOI18N

        chkImport.setText("Import");
        chkImport.setEnabled(false);
        chkImport.setName("chkImport"); // NOI18N

        chkDelete.setText("Suppression");
        chkDelete.setEnabled(false);
        chkDelete.setName("chkDelete"); // NOI18N

        chkSearch.setText("Recherche");
        chkSearch.setEnabled(false);
        chkSearch.setName("chkSearch"); // NOI18N

        chkNavigate.setText("Navigation");
        chkNavigate.setEnabled(false);
        chkNavigate.setName("chkNavigate"); // NOI18N

        chkExport.setText("Export");
        chkExport.setEnabled(false);
        chkExport.setName("chkExport"); // NOI18N

        chkAdminUser.setText("Administration utilisateurs");
        chkAdminUser.setEnabled(false);
        chkAdminUser.setName("chkAdminUser"); // NOI18N

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 266, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(pbRemoveProfil, 0, 0, Short.MAX_VALUE)
                            .add(pbAddProfil, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 32, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .add(18, 18, 18)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(chkImport)
                            .add(chkConnect)
                            .add(chkDelete)
                            .add(chkSearch)
                            .add(chkNavigate)
                            .add(chkExport)
                            .add(chkAdminUser))
                        .addContainerGap())
                    .add(layout.createSequentialGroup()
                        .add(jLabel1)
                        .addContainerGap(484, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(pbAddProfil)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(pbRemoveProfil))
                    .add(layout.createSequentialGroup()
                        .add(chkConnect)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(chkImport)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(chkDelete)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(chkSearch)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(chkNavigate)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(chkExport)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(chkAdminUser))
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void pbAddProfilActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbAddProfilActionPerformed
        DlgCreateCodeLib dlg = new DlgCreateCodeLib(dlgAdmin, "Nouveau profil", "Profil");
        if(dlg.run()) {
            Pair ret = dlg.getRet();
            Profil profil = new Profil(ret.key,ret.libelle);
            if(DataHelper.createProfil(profil)) {
                lm.addProfil(profil);
            }
        }
    }//GEN-LAST:event_pbAddProfilActionPerformed

    private void pbRemoveProfilActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbRemoveProfilActionPerformed
        Profil profil = (Profil)lstProfils.getSelectedValue();
        if(JOptionPane.showConfirmDialog(this, "Etes-vous bien sūr de vouloir supprimer le profil "+profil.getLibelle()+" ?")==JOptionPane.YES_OPTION) {
            if(DataHelper.removeProfil(profil)) {
                lm.removeProfil(profil);
            }
        }
    }//GEN-LAST:event_pbRemoveProfilActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JCheckBox chkAdminUser;
    private javax.swing.JCheckBox chkConnect;
    private javax.swing.JCheckBox chkDelete;
    private javax.swing.JCheckBox chkExport;
    private javax.swing.JCheckBox chkImport;
    private javax.swing.JCheckBox chkNavigate;
    private javax.swing.JCheckBox chkSearch;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JList lstProfils;
    private javax.swing.JButton pbAddProfil;
    private javax.swing.JButton pbRemoveProfil;
    // End of variables declaration//GEN-END:variables

    private class ProfilListModel extends AbstractListModel {
        private TreeSet<Profil> data;

        public ProfilListModel(ArrayList<Profil> data) {
            this.data = new TreeSet<Profil>();
            this.data.addAll(data);
        }

        public Object getElementAt(int index) {
            Iterator<Profil> it = data.iterator();
            for(int i=0;i<index;i++) {
                it.next();
            }
            return it.next();
        }

        public int getSize() {
            return this.data.size();
        }
        
        protected int getIndexOf(Profil profil) {
            Iterator<Profil> it = data.iterator();
            for(int i=0;i<data.size();i++) {
                Profil p = it.next();
                if(p.equals(profil)) return i;
            }
            return -1;
        }
        public void addProfil(Profil profil) {
            if(!data.contains(profil)) {
                data.add(profil);
                int pos = getIndexOf(profil);
                fireIntervalAdded(lstProfils, pos, pos);
                lstProfils.setSelectedIndex(pos);
            }
        }

        public void removeProfil(Profil profil) {
            int pos = getIndexOf(profil);
            data.remove(profil);
            fireIntervalRemoved(lstProfils, pos, pos);
        }

    }
    private class ChkActionListener implements ActionListener {
        private String fonctionnalite;
        public ChkActionListener(String fonctionnalite) {
            super();
            this.fonctionnalite=fonctionnalite;
        }
        public void actionPerformed(ActionEvent e) {
            JCheckBox chk = (JCheckBox)e.getSource();
            boolean selected = chk.isSelected();
            Profil p = (Profil)lstProfils.getSelectedValue();
            if(selected) p.getFonctionnalites().add(fonctionnalite);
            else p.getFonctionnalites().remove(fonctionnalite);
            DataHelper.saveProfil(p);
//            System.out.println(((JCheckBox)e.getSource()).getName().concat(" changed"));
        }

    }
}
