/*
 * Copyright
 *   2008 axYus - www.axyus.com
 *   2008 C.Marchand - christophe.marchand@axyus.com
 *   2008 C.Bosquet - charles.bosquet@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 fr.gouv.finances.dgfip.xemelios.auth.AuthEngine;
import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser.SimpleXemeliosUserImpl;
import fr.gouv.finances.dgfip.xemelios.common.Crypter;
import fr.gouv.finances.dgfip.xemelios.data.DataConfigurationException;
import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
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.PStmtBinder.SimplePStmtBinderBuilder;
import fr.gouv.finances.dgfip.xemelios.data.utils.jdbc.RowMapper;
import fr.gouv.finances.dgfip.xemelios.data.utils.jdbc.RowMapper.ColToIntegerRowMapper;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Set;
import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import org.apache.log4j.Logger;

/**
 * @author CHM
 * @author CBO
 */
public class DgcpAuthEngine implements AuthEngine {
    private static final Logger logger = Logger.getLogger(DgcpAuthEngine.class);

	public static final transient int ROLE_ADMIN_BIT = 0x1000;
    public static final transient String ROLE_ADMIN = "DGCP_ADMIN";

    private String serviceProvider;
    private String ldapUrl;
    private String baseDn;

    public DgcpAuthEngine() throws SQLException, DataConfigurationException {
        Connection connection = null;
        try {
            connection = PoolManager.getInstance().getConnection();
            String sql = "CREATE TABLE IF NOT EXISTS DGCP_USERS (LOGIN VARCHAR(24) NOT NULL, PASSWORD VARCHAR(128), ACCESS INT, CONSTRAINT UN_LOGIN UNIQUE (LOGIN))";
            JdbcUtils.executeUpdate(connection, sql);
            long userCount = (Long) JdbcUtils.queryObject(connection, "SELECT COUNT(*) FROM DGCP_USERS", new RowMapper.ColToLongRowMapper());
            if (userCount <= 0) {
                NewAdmin na = new NewAdmin(null);
                if (na.run()) {
                    JdbcUtils.executeUpdate(connection,
                            "INSERT INTO DGCP_USERS(LOGIN,PASSWORD,ACCESS) VALUES (?,?,?)",
                            new SimplePStmtBinderBuilder().add(na.getNewLogin()).add(Crypter.cryptPassword(na.getNewPassword())).add(0xFFFF).toPStmtBinder());
                } else {
                    System.exit(0); // TODO : voir si c'est raisonnable
                }
            }
        } finally {
            PoolManager.getInstance().releaseConnection(connection);
        }
        serviceProvider = DataLayerManager.getImplementation().getParameterValue("auth.ldap.service.provider");
        ldapUrl = DataLayerManager.getImplementation().getParameterValue("auth.ldap.server.url");
        baseDn = DataLayerManager.getImplementation().getParameterValue("auth.ldap.userDn");
        if (serviceProvider == null) {
            throw new RuntimeException("you must configure service provider in auth.ldap.service.provider parameter");
        }
        if (ldapUrl == null) {
            throw new RuntimeException("You must configure ldap server url in auth.ldap.server.url parameter");
        }
        if (baseDn == null) {
            throw new RuntimeException("You must configure the base dn in auth.ldap.userDn parameter");
        }
    }

    public boolean isLoginRequired() {
        return true;
    }

    public boolean isPasswordRequired() {
        return true;
    }

    public XemeliosUser createUser(String login, String password) {
        Connection connection = null;
        try {
            connection = PoolManager.getInstance().getConnection();
            if (authenticateLDAP(login, password) || authenticateAdmin(connection, login, password)) {
                Integer rolesAsInt = getRolesAsInt(connection, login);
                if (rolesAsInt == null) {
                    rolesAsInt = XemeliosUser.ROLE_CONNECT_BIT | XemeliosUser.ROLE_SEARCH_BIT | XemeliosUser.ROLE_BROWSE_BIT | XemeliosUser.ROLE_EXPORT_BIT;
                    JdbcUtils.executeUpdate(connection,
                            "INSERT INTO DGCP_USERS (LOGIN, ACCESS) VALUES (?, ?)",
                            new SimplePStmtBinderBuilder().add(login).add(rolesAsInt).toPStmtBinder());
                    connection.commit();
                }
                XemeliosUser toReturn = new SimpleXemeliosUserImpl(login, login,
                            false, rolesFromInt(rolesAsInt), true, null, true, null);
                if (toReturn.hasRole(XemeliosUser.ROLE_CONNECT) && toReturn.hasRole(ROLE_ADMIN)) {
                    insertAdminMenu();
                }
                return toReturn;
            } else {
                return null;
            }
        } catch (SQLException sqle) {
            throw new SQLRuntimeException(sqle);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            PoolManager.getInstance().releaseConnection(connection);
        }
    }

    private Integer getRolesAsInt(Connection connection, String login) throws SQLException {
        return (Integer)JdbcUtils.queryObject(connection,
                "SELECT ACCESS FROM DGCP_USERS WHERE LOGIN = ?",
                new ColToIntegerRowMapper(),
                new SimplePStmtBinderBuilder().add(login).toPStmtBinder());
    }

	private boolean authenticateLDAP(String login, String password) throws DataConfigurationException {
		DirContext dctx = null;
		Hashtable<String,String> env = new Hashtable<String,String>();
		env.put(Context.INITIAL_CONTEXT_FACTORY, serviceProvider);
		env.put(Context.PROVIDER_URL, ldapUrl);
		env.put(Context.SECURITY_AUTHENTICATION, "simple");
		String userDn = baseDn.replaceAll("%LOGIN%", login);
		env.put(Context.SECURITY_PRINCIPAL, userDn);
		env.put(Context.SECURITY_CREDENTIALS, password);
		try {
			dctx = new InitialDirContext(env);
			dctx.close();
		} catch(AuthenticationException aEx) {
			return false;
		} catch (NamingException naEx) {
			return false;
		}
		return true;
	}

	private boolean authenticateAdmin(Connection con, String login, String password) throws SQLException {
        Integer rolesAsInt = (Integer)JdbcUtils.queryObject(con,
                "SELECT ACCESS FROM DGCP_USERS WHERE LOGIN = ? AND PASSWORD = ?",
                new ColToIntegerRowMapper(),
                new SimplePStmtBinderBuilder().add(login).add(Crypter.cryptPassword(password)).toPStmtBinder());
        return rolesAsInt != null && (ROLE_ADMIN_BIT & rolesAsInt.intValue()) > 0;
	}

    public boolean modifyPassword(String login, String password) throws SQLException {
        Connection connection = null;
        try {
            connection = PoolManager.getInstance().getConnection();
            return JdbcUtils.executeUpdate(connection, "UPDATE DGCP_USERS SET PASSWORD = ? WHERE LOGIN = ?",
                    new SimplePStmtBinderBuilder().add(Crypter.cryptPassword(password)).add(login).toPStmtBinder()).getCountUpdated() == 1;
        } finally {
            PoolManager.getInstance().releaseConnection(connection);
        }
    }

	public void updateAuthUser(String login, Integer access) throws SQLException {
        Connection connection = null;
        try {
            connection = PoolManager.getInstance().getConnection();
            JdbcUtils.executeUpdate(connection, "UPDATE DGCP_USERS SET ACCESS = ? WHERE LOGIN = ?",
                    new SimplePStmtBinderBuilder().add(access).add(login).toPStmtBinder()).getCountUpdated();
        } finally {
            PoolManager.getInstance().releaseConnection(connection);
        }
	}

	public boolean create(String login, Integer rolesAsInt) throws SQLException {
        Connection connection = null;
        boolean toReturn = true;
        try {
            connection = PoolManager.getInstance().getConnection();
            return JdbcUtils.executeUpdate(connection, "INSERT INTO DGCP_USERS (LOGIN, ACCESS) VALUES (?,?)",
                    new SimplePStmtBinderBuilder().add(login).add(rolesAsInt).toPStmtBinder()).getCountUpdated() == 1;
        } catch(SQLException sqle) {
            toReturn = false; // TODO : A gérer correctement
        } finally {
            PoolManager.getInstance().releaseConnection(connection);
        }
        return toReturn;
	}

	protected void insertAdminMenu() {
        boolean doNotStop = false;
        Class clazz = null;
        Object instance = null;
        try {
            clazz = Class.forName("fr.gouv.finances.cp.xemelios.ui.MainWindow");
            Method meth = clazz.getMethod("getInstance");
            instance = meth.invoke(null);
            doNotStop = (instance!=null);
        } catch(NullPointerException npEx) {
        } catch(Throwable t) {
        }
        if(doNotStop) {
            final Object inst = instance;
            JMenu adminMenu = new JMenu("Administration");
            JMenuItem item = new JMenuItem("Gestion des utlisateurs...");
            item.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    new DlgAdminUsers((JFrame)inst);
                }
            });
            adminMenu.add(item);
            JMenuBar mBar = null;
            try {
                Method meth = clazz.getMethod("getJMenuBar");
                mBar = (JMenuBar)meth.invoke(inst);
            } catch(Throwable t) {}
            if(mBar!=null) {
                int mnuCount = mBar.getMenuCount();
                JMenu helpMenu = mBar.getMenu(mnuCount - 1);
                mBar.add(adminMenu);
                mBar.add(helpMenu);
                try {
                    Method meth = clazz.getMethod("setJMenuBar", JMenuBar.class);
                    meth.invoke(inst, mBar);
                } catch(Throwable t) {}
            }
        }
//            JMenuBar mBar = MainWindow.getInstance().getJMenuBar();
//            int mnuCount = mBar.getMenuCount();
//            JMenu helpMenu = mBar.getMenu(mnuCount - 1);
//            mBar.add(adminMenu);
//            mBar.add(helpMenu);
//            MainWindow.getInstance().setJMenuBar(mBar);
	}

    private Collection<String> rolesFromInt(int rolesAsInt) {
        Set toReturn = new HashSet();
        if ((rolesAsInt & XemeliosUser.ROLE_BROWSE_BIT) > 0) {
            toReturn.add(XemeliosUser.ROLE_BROWSE);
        }
        if ((rolesAsInt & XemeliosUser.ROLE_CLEAN_BIT) > 0) {
            toReturn.add(XemeliosUser.ROLE_CLEAN);
        }
        if ((rolesAsInt & XemeliosUser.ROLE_CONNECT_BIT) > 0) {
            toReturn.add(XemeliosUser.ROLE_CONNECT);
        }
        if ((rolesAsInt & XemeliosUser.ROLE_EXPORT_BIT) > 0) {
            toReturn.add(XemeliosUser.ROLE_EXPORT);
        }
        if ((rolesAsInt & XemeliosUser.ROLE_IMPORT_BIT) > 0) {
            toReturn.add(XemeliosUser.ROLE_IMPORT);
        }
        if ((rolesAsInt & XemeliosUser.ROLE_SEARCH_BIT) > 0) {
            toReturn.add(XemeliosUser.ROLE_SEARCH);
        }
        if ((rolesAsInt & ROLE_ADMIN_BIT) > 0) {
            toReturn.add(ROLE_ADMIN);
        }
        return toReturn;
    }

}
