/*
 * Copyright 
 *   2005 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 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.cp.xemelios.auth.dgcp;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.event.TableModelEvent;
import javax.swing.table.AbstractTableModel;

import org.jdesktop.swingx.JXTable;

import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
import fr.gouv.finances.cp.xemelios.data.impl.MySqlDataLayer;
import fr.gouv.finances.cp.xemelios.ui.MainWindow;
import fr.gouv.finances.dgfip.xemelios.auth.AuthEngine;
import fr.gouv.finances.dgfip.xemelios.data.impl.pool.PoolManager;
import fr.gouv.finances.dgfip.xemelios.data.impl.pool.SQLRuntimeException;
import fr.gouv.finances.dgfip.xemelios.data.utils.jdbc.JdbcUtils;
import fr.gouv.finances.dgfip.xemelios.data.utils.jdbc.RowHandler;

public class DlgAdminUsers extends JDialog {

	private static final long serialVersionUID = -139419090026420451L;
	private JXTable table = null;
	private UsersModel model = null;

	public DlgAdminUsers(Frame owner) throws HeadlessException {
		super(owner,"Gestion des utilisateurs");
		initialize();
	}

	protected void initialize() {
		JPanel pane = new JPanel(new BorderLayout());
		JPanel centerPane = new JPanel(new FlowLayout());
		JButton pbAddUser = new JButton("Nouvel utilisateur...");
		centerPane.add(pbAddUser);
		JButton pbOk = new JButton("Fermer");
		centerPane.add(pbOk);
                JPanel buttonPane = new JPanel(new BorderLayout());
                buttonPane.add(centerPane,BorderLayout.EAST);
                JButton pbChangPassword = new JButton("Changer le mot de passe...");
                JPanel tmpPane = new JPanel(new FlowLayout());
                tmpPane.add(pbChangPassword);
                buttonPane.add(tmpPane,BorderLayout.WEST);
		pane.add(buttonPane,BorderLayout.SOUTH);
		MySqlDataLayer layer = null;
		try {
			layer = (MySqlDataLayer)DataLayerManager.getImplementation();
		} catch(Throwable t) {}
		
		pbOk.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				setVisible(false);
				dispose();
			}
		});
                pbChangPassword.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        DlgChangePassword chgPwd = new DlgChangePassword(MainWindow.instance,true);
                        chgPwd.setVisible(true);
                    }
                });
		if(layer!=null) {
			pbAddUser.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					addNewUser();
				}
			});
		}
		
		model = new UsersModel();
		table = new JXTable(model);
		pane.add(new JScrollPane(table),BorderLayout.CENTER);
		
		table.setColumnControlVisible(true);
		
		
		setContentPane(pane);
		pack();
		setLocationRelativeTo(getOwner());
		setVisible(true);
	}

    private DgcpAuthEngine getAuthEngine() {
        return (DgcpAuthEngine)AuthEngine.Holder.getAuthEngine();
    }

	private void addNewUser() {
		String id = JOptionPane.showInputDialog(this,"Saisissez l'identifiant de l'utilisateur à créer :");
		if(id!=null) {
			try {
                if (!getAuthEngine().create(id, XemeliosUser.ROLE_CONNECT_BIT)) {
                    JOptionPane.showMessageDialog(this,"Cet utilisateur existe déjà.","Attention",JOptionPane.WARNING_MESSAGE);
                } else {
					model.refresh();
					table.tableChanged(new TableModelEvent(model));
				}
			} catch(Throwable t) {}
		}
	}

	@SuppressWarnings("serial")
	private class UsersModel extends AbstractTableModel {
		
		private Vector<UserVO> users = null;
		
		public UsersModel() {
			super();
            users = new Vector<UserVO>();
			refresh();
		}

		public int getColumnCount() {
			return 8;
		}

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

		public Object getValueAt(int rowIndex, int columnIndex) {
			UserVO user = users.elementAt(rowIndex);
			switch(columnIndex) {
			case 0:	return user.login;
			case 1: return new Boolean((user.auth & XemeliosUser.ROLE_CONNECT_BIT)>0);
			case 2: return new Boolean((user.auth & XemeliosUser.ROLE_SEARCH_BIT)>0);
			case 3: return new Boolean((user.auth & XemeliosUser.ROLE_BROWSE_BIT)>0);
			case 4: return new Boolean((user.auth & XemeliosUser.ROLE_EXPORT_BIT)>0);
			case 5: return new Boolean((user.auth & XemeliosUser.ROLE_IMPORT_BIT)>0);
			case 6: return new Boolean((user.auth & XemeliosUser.ROLE_CLEAN_BIT)>0);
			case 7: return new Boolean((user.auth & DgcpAuthEngine.ROLE_ADMIN_BIT)>0);
			}
			return null;
		}

		@Override
		public Class<?> getColumnClass(int columnIndex) {
			if(columnIndex==0) return String.class;
			return Boolean.class;
		}

		@Override
		public String getColumnName(int column) {
			switch(column) {
			case 0: return "Identifiant";
			case 1: return "Connexion";
			case 2: return "Recherche";
			case 3: return "Navigation";
			case 4: return "Export";
			case 5: return "Import";
			case 6: return "Suppression";
			case 7: return "Administration";
			}
			return "";
		}

		@Override
		public boolean isCellEditable(int rowIndex, int columnIndex) {
			if(columnIndex==0) return false;
			return true;
		}

		@Override
		public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
			boolean newValue = ((Boolean)(aValue)).booleanValue();
			int bit = 0;
			switch(columnIndex) {
			case 1: bit = XemeliosUser.ROLE_CONNECT_BIT; break;
			case 2: bit = XemeliosUser.ROLE_SEARCH_BIT; break;
			case 3: bit = XemeliosUser.ROLE_BROWSE_BIT; break;
			case 4: bit = XemeliosUser.ROLE_EXPORT_BIT; break;
			case 5: bit = XemeliosUser.ROLE_IMPORT_BIT; break;
			case 6: bit = XemeliosUser.ROLE_CLEAN_BIT; break;
			case 7: bit = DgcpAuthEngine.ROLE_ADMIN_BIT;
			}
			if(bit==0) return;
			UserVO user = users.elementAt(rowIndex);
			int auth = newValue ? user.auth | bit:~bit & user.auth;
			user.auth = auth;
			try {
                getAuthEngine().updateAuthUser(user.login, user.auth);
			} catch(Throwable t) {}
		}

		private void refresh() {
            Connection connection = null;
            try {
                connection = PoolManager.getInstance().getConnection();
                JdbcUtils.fetchSQL(connection, "SELECT LOGIN, ACCESS FROM DGCP_USERS ORDER BY LOGIN", new RowHandler() {

                    public boolean handleRow(ResultSet rs) throws SQLException {
                        users.add(new UserVO(rs.getString(1), rs.getInt(2)));
                        return true;
                    }
                });
                
            } catch(SQLException sqle) {
                throw new SQLRuntimeException(sqle);
            } finally {
                PoolManager.getInstance().releaseConnection(connection);
            }
		}

	}

    static private class UserVO {

        private UserVO(String login, int auth) {
            this.login = login;
            this.auth = auth;
        }

        public String login;
        public int auth;
    }
}
