/*
 * 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.xemelios.auth.Collectivite;
import fr.gouv.finances.dgfip.xemelios.auth.impl.std.db.ui.DataHelper.CollectiviteLib;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author chm
 */
public class DlgCollectivitesUtilisateur extends javax.swing.JDialog {
    public static final Hashtable<String,String> naturesIdentifiants;
    static {
        naturesIdentifiants = new Hashtable<String,String>();
        naturesIdentifiants.put("SIRET","SIRET");
        naturesIdentifiants.put("IDCOLL","Identifiant DGFiP");
        naturesIdentifiants.put("CODIC","Poste comptable");
        naturesIdentifiants.put("VARIABLE", "Divers");
    }

    private DataHelper.StdUser user;
    private TableCollectivitesModel collectivitesUserModel;
    private boolean bRet;

    /** Creates new form DlgCollectivitesUtilisateur */
    public DlgCollectivitesUtilisateur(java.awt.Dialog parent, DataHelper.StdUser user) {
        super(parent, "Collectivités", true);
        this.user=user;
        collectivitesUserModel = new TableCollectivitesModel(user.getCollectivites());
        initComponents();
        tblCollectivitesUser.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                pbRemoveCollectivite.setEnabled(tblCollectivitesUser.getSelectedRowCount()>0);
            }
        });
        tblCollectivitesUser.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        setLocationRelativeTo(parent);
    }
    public boolean run() {
        bRet = false;
        setVisible(true);
        return bRet;
    }


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

        jScrollPane1 = new javax.swing.JScrollPane();
        tblCollectivitesUser = new org.jdesktop.swingx.JXTable();
        pbCancel = new javax.swing.JButton();
        pbOk = new javax.swing.JButton();
        lblHeader = new javax.swing.JLabel();
        pbAddCollectivite = new javax.swing.JButton();
        pbRemoveCollectivite = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        tblCollectivitesUser.setModel(collectivitesUserModel);
        jScrollPane1.setViewportView(tblCollectivitesUser);

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

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

        lblHeader.setText("Collectivités de "+user.toString());

        pbAddCollectivite.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fr/gouv/finances/cp/xemelios/ui/resources/add.png"))); // NOI18N
        pbAddCollectivite.setToolTipText("Ajouter une collectivité");
        pbAddCollectivite.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pbAddCollectiviteActionPerformed(evt);
            }
        });

        pbRemoveCollectivite.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fr/gouv/finances/cp/xemelios/ui/resources/deleteRow.png"))); // NOI18N
        pbRemoveCollectivite.setToolTipText("Supprimer cette collectivité");
        pbRemoveCollectivite.setEnabled(false);
        pbRemoveCollectivite.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pbRemoveCollectiviteActionPerformed(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(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 328, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                            .add(pbRemoveCollectivite, 0, 0, Short.MAX_VALUE)
                            .add(pbAddCollectivite, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 32, Short.MAX_VALUE)))
                    .add(lblHeader)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(pbCancel)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(pbOk)))
                .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(pbAddCollectivite)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(pbRemoveCollectivite))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 241, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .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
        setVisible(false);
}//GEN-LAST:event_pbCancelActionPerformed

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

    private void pbAddCollectiviteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbAddCollectiviteActionPerformed
        DlgSelectCollectivite dlg = new DlgSelectCollectivite(this);
        if(dlg.run()) {
            for(CollectiviteLib coll: dlg.getSelectedData()) {
                collectivitesUserModel.addCollectivite(coll);
            }
            
        }
}//GEN-LAST:event_pbAddCollectiviteActionPerformed

    private void pbRemoveCollectiviteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbRemoveCollectiviteActionPerformed
        int[] rows = tblCollectivitesUser.getSelectedRows();
        Arrays.sort(rows);
        for(int i=rows.length-1;i>=0;i--) {
            collectivitesUserModel.removeRow(rows[i]);
        }
}//GEN-LAST:event_pbRemoveCollectiviteActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblHeader;
    private javax.swing.JButton pbAddCollectivite;
    private javax.swing.JButton pbCancel;
    private javax.swing.JButton pbOk;
    private javax.swing.JButton pbRemoveCollectivite;
    private org.jdesktop.swingx.JXTable tblCollectivitesUser;
    // End of variables declaration//GEN-END:variables

    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;
    }

    public static class TableCollectivitesModel extends AbstractTableModel {
        public static final long serialVersionUID = 1L;
        private ArrayList<CollectiviteLib> data;

        public TableCollectivitesModel(ArrayList<CollectiviteLib> data) {
            super();
            this.data=data;
        }

        public int getRowCount() {
            return data.size();
        }

        public int getColumnCount() {
            return 3;
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            CollectiviteLib coll = data.get(rowIndex);
            switch(columnIndex) {
                case 0: return getTypIdLib(coll.getNatureIdentifiant());
                case 1: return coll.getClef();
                default: return coll.getLibelle();
            }
        }
        public void addCollectivite(CollectiviteLib coll) {
            data.add(coll);
            fireTableRowsInserted(data.size()-1, data.size());
        }
        public CollectiviteLib getElementAt(int pos) {
            return data.get(pos);
        }
        public Collectivite removeCollectivite(Collectivite coll) {
            int pos = data.indexOf(coll);
            if(pos>=0) {
                data.remove(pos);
                fireTableRowsDeleted(pos, pos);
            }
            return coll;
        }
        public CollectiviteLib removeRow(int row) {
            CollectiviteLib ret = data.remove(row);
            fireTableRowsDeleted(row, row);
            return ret;
        }

        @Override
        public String getColumnName(int column) {
            switch(column) {
                case 0: return "Nature identifiant";
                case 1: return "Identifiant";
                default: return "Libellé";
            }
        }

        public void setData(ArrayList<CollectiviteLib> data) {
            this.data=data;
            fireTableDataChanged();
        }

    }

    public static String getTypIdLib(String natureIdentifiant) {
        return naturesIdentifiants.get(natureIdentifiant);
    }
}
