/*
 * Copyright
 *   2008 axYus - www.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.dgfip.xemelios.auth.impl.std.db;

import fr.gouv.finances.dgfip.xemelios.auth.AuthEngine;
import fr.gouv.finances.dgfip.xemelios.auth.DbAuthEngineHelper;
import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser.SimpleXemeliosUserImpl;
import fr.gouv.finances.dgfip.xemelios.auth.impl.std.db.ui.DlgAdmin;
import fr.gouv.finances.dgfip.xemelios.data.impl.pool.PoolManager;
import fr.gouv.finances.dgfip.xemelios.data.impl.pool.SQLRuntimeException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

/**
 * @author CBO
 */
public class StdDbAuthEngineImpl implements AuthEngine {

    public static final String ROLE_ADMIN = "USER_ADMIN";

    public StdDbAuthEngineImpl(boolean createAdmin) throws SQLException {
        DbAuthEngineHelper.checkDBStruct(createAdmin);
    }
    public StdDbAuthEngineImpl() throws SQLException {
        DbAuthEngineHelper.checkDBStruct(true);
    }

    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 (DbAuthEngineHelper.authenticate(connection, login, password)) {
                XemeliosUser ret = doCreateUser(connection, login);

                return ret;
            } else {
                return null;
            }
        } catch (SQLException sqle) {
            throw new SQLRuntimeException(sqle);
        } finally {
            PoolManager.getInstance().releaseConnection(connection);
        }
    }

    protected XemeliosUser doCreateUser(Connection connection, String login) throws SQLException {
       if(!DbAuthEngineHelper.userExists(connection, login) ) {
          return null;
       }


       XemeliosUser ret = new SimpleXemeliosUserImpl(login, login,
                DbAuthEngineHelper.userHasAllFonctionnalites(connection, login),
                DbAuthEngineHelper.getFonctionnalitesByLogin(connection, login),
                DbAuthEngineHelper.userHasAllDocuments(connection, login),
                DbAuthEngineHelper.getDocumentsByLogin(connection, login),
                DbAuthEngineHelper.userHasAllCollectivites(connection, login),
                DbAuthEngineHelper.getCollectivitesByLogin(connection, login));

        if (ret !=null && ret.hasRole(XemeliosUser.ROLE_CONNECT) && ret.hasRole(ROLE_ADMIN)) {
            insertAdminMenu();
        }
        return ret;



    }

    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 (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) {
                    DlgAdmin dlg = new DlgAdmin((JFrame) inst);
                    dlg.setVisible(true);
                }
            });
            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) {
                }
            }
        }
    }
}