/*
 * 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.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.sql.Statement;
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.cp.xemelios.auth.AuthenticationFactory;
import fr.gouv.finances.cp.xemelios.auth.XemeliosUser;
import fr.gouv.finances.cp.xemelios.data.DataLayerManager;
import fr.gouv.finances.cp.xemelios.data.impl.MySqlDataLayer;
import fr.gouv.finances.cp.xemelios.ui.MainWindow;

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) {
			final MySqlDataLayer aLayer = layer;
			pbAddUser.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					addNewUser(aLayer);
				}
			});
		}
		
		model = new UsersModel(layer);
		table = new JXTable(model);
		pane.add(new JScrollPane(table),BorderLayout.CENTER);
		
		table.setColumnControlVisible(true);
		
		
		setContentPane(pane);
		pack();
		setLocationRelativeTo(getOwner());
		setVisible(true);
	}
	private void addNewUser(MySqlDataLayer layer) {
		String id = JOptionPane.showInputDialog(this,"Saisissez l'identifiant de l'utilisateur à créer :");
		if(id!=null) {
			DgcpUser user = new DgcpUser(id,XemeliosUser.ROLE_CONNECT);
			try {
				Manager manager = (Manager)AuthenticationFactory.getManager((MainWindow)getOwner());
				if(!manager.create(user)) 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<DgcpUser> users = null;
		private MySqlDataLayer layer = null;
		
		public UsersModel(MySqlDataLayer layer) {
			super();
			this.layer = layer;
			refresh();
		}

		public int getColumnCount() {
			return 8;
		}

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

		public Object getValueAt(int rowIndex, int columnIndex) {
			DgcpUser user = users.elementAt(rowIndex);
			switch(columnIndex) {
			case 0:	return user.getId();
			case 1: return new Boolean((user.getAuth(null) & XemeliosUser.ROLE_CONNECT)>0);
			case 2: return new Boolean((user.getAuth(null) & XemeliosUser.ROLE_SEARCH)>0);
			case 3: return new Boolean((user.getAuth(null) & XemeliosUser.ROLE_BROWSE)>0);
			case 4: return new Boolean((user.getAuth(null) & XemeliosUser.ROLE_EXPORT)>0);
			case 5: return new Boolean((user.getAuth(null) & XemeliosUser.ROLE_IMPORT)>0);
			case 6: return new Boolean((user.getAuth(null) & XemeliosUser.ROLE_CLEAN)>0);
			case 7: return new Boolean((user.getAuth(null) & DgcpUser.ROLE_ADMIN)>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; break;
			case 2: bit=XemeliosUser.ROLE_SEARCH; break;
			case 3: bit=XemeliosUser.ROLE_BROWSE; break;
			case 4: bit=XemeliosUser.ROLE_EXPORT; break;
			case 5: bit=XemeliosUser.ROLE_IMPORT; break;
			case 6: bit=XemeliosUser.ROLE_CLEAN; break;
			case 7: bit=DgcpUser.ROLE_ADMIN;
			}
			if(bit==0) return;
			DgcpUser user = users.elementAt(rowIndex);
			int auth = newValue?user.getAuth(null)|bit:~bit&user.getAuth(null);
			user.setAuth(auth);
			try {
				Manager manager = (Manager)AuthenticationFactory.getManager((MainWindow)getOwner());
				manager.updateAuthUser(user);users.setElementAt(user,rowIndex);
			} catch(Throwable t) {}
		}
		private void refresh() {
			Connection con = null;
			Statement st = null;
			ResultSet rs = null;
			try {
				users = new Vector<DgcpUser>();
				con = layer.getConnection();
				String sql = "SELECT LOGIN, ACCESS FROM DGCP_USERS ORDER BY LOGIN";
				st = con.createStatement();
				rs = st.executeQuery(sql);
				while(rs.next()) 
					users.add(
							new DgcpUser(
									rs.getString(1),
									rs.getInt(2)));
			} catch(SQLException sqlEx) {
				sqlEx.printStackTrace();
			} finally {
				if(rs!=null) try { rs.close(); } catch(Throwable t) {}
				if(st!=null) try { st.close(); } catch(Throwable t) {}
				if(con!=null) layer.releaseConnection(con);
			}
		}
	}
}
