/*
 * Copyright
 *   2005 axYus - www.axyus.com
 *   2005 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.dgfip.xemelios.auth.impl.basic;

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.common.Crypter;
import fr.gouv.finances.dgfip.xemelios.data.DataImpl;
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 java.sql.Connection;
import java.sql.SQLException;

/**
 * @author CHM
 * @author CBO
 */
public class BasicAuthEngineImpl implements AuthEngine {

    static private final String STD_PROFIL_CODE = "_basic_user";
    static private final String STD_PROFIL_LIBELLE = "Utilisateurs standards";
    static private final long STD_USER_ID = 1;
    static private final String STD_USER_LOGIN = "_basic_user";
    static private final String ADM_PROFIL_CODE = "_basic_admin";
    static private final String ADM_PROFIL_LIBELLE = "Administrateurs";
    static private final long ADM_USER_ID = 2;
    static private final String ADM_USER_LOGIN = "_basic_admin";

    public BasicAuthEngineImpl() throws SQLException {
        DbAuthEngineHelper.checkDBStruct();
        Connection connection = null;
        try {
            connection = PoolManager.getInstance().getConnection();
            connection.setAutoCommit(false);
            createAccountIfNeeded(connection);
            connection.commit();
        } catch (SQLException sqle) {
            throw new SQLRuntimeException(sqle);
        } finally {
            PoolManager.getInstance().releaseConnection(connection);
        }
    }

    public boolean isLoginRequired() {
        return false;
    }

    public boolean isPasswordRequired() {
        return true;
    }

    public XemeliosUser createUser(String unusedLogin, String password) {
        Connection connection = null;
        try {
            connection = PoolManager.getInstance().getConnection();
            String userLogin = getUserLoginByPassword(connection, password);
            if (userLogin != null) {
                return new SimpleXemeliosUserImpl(userLogin, userLogin,
                        DbAuthEngineHelper.userHasAllFonctionnalites(connection, userLogin),
                        DbAuthEngineHelper.getFonctionnalitesByLogin(connection, userLogin),
                        DbAuthEngineHelper.userHasAllDocuments(connection, userLogin),
                        DbAuthEngineHelper.getDocumentsByLogin(connection, userLogin),
                        DbAuthEngineHelper.userHasAllCollectivites(connection, userLogin),
                        DbAuthEngineHelper.getCollectivitesByLogin(connection, userLogin));
            } else {
                return null;
            }
        } catch (SQLException sqle) {
            throw new SQLRuntimeException(sqle);
        } finally {
            PoolManager.getInstance().releaseConnection(connection);
        }
    }

    private void createAccountIfNeeded(Connection connection) throws SQLException {
        long userCount = (Long) JdbcUtils.queryObject(connection,
                "SELECT COUNT(*) FROM AUTH_UTILISATEUR", new RowMapper.ColToLongRowMapper());
        if (userCount <= 0) {
            BasicAuthEngineConfiguationDialog confDialog = new BasicAuthEngineConfiguationDialog(null);
            if (confDialog.run()) {
                // Création des profils :
                DbAuthEngineHelper.createProfil(connection, STD_PROFIL_CODE, STD_PROFIL_LIBELLE,
                        new String[]{XemeliosUser.ROLE_CONNECT, XemeliosUser.ROLE_SEARCH, XemeliosUser.ROLE_BROWSE, XemeliosUser.ROLE_EXPORT});
                DbAuthEngineHelper.createProfil(connection, ADM_PROFIL_CODE, ADM_PROFIL_LIBELLE,
                        new String[]{XemeliosUser.ROLE_CONNECT, XemeliosUser.ROLE_SEARCH, XemeliosUser.ROLE_BROWSE, XemeliosUser.ROLE_EXPORT, XemeliosUser.ROLE_IMPORT, XemeliosUser.ROLE_CLEAN});
                // Création des utilisateurs :
                DbAuthEngineHelper.createUser(connection, STD_USER_ID, STD_USER_LOGIN,
                        Crypter.cryptPassword(confDialog.getNewPassword()[DataImpl.READ_ONLY_PASS]), null, null, false, true, true, new String[]{STD_PROFIL_CODE});
                DbAuthEngineHelper.createUser(connection, ADM_USER_ID, ADM_USER_LOGIN,
                        Crypter.cryptPassword(confDialog.getNewPassword()[DataImpl.READ_WRITE_PASS]), null, null, false, true, true, new String[]{ADM_PROFIL_CODE});
            } else {
                System.exit(0); // TODO : voir si c'est raisonnable
            }
        }
    }

    private String getUserLoginByPassword(Connection connection, String password) throws SQLException {
        return (String) JdbcUtils.queryObject(connection,
                "SELECT U.UTI_LOGIN FROM AUTH_UTILISATEUR U WHERE U.UTI_PASSWORD = ?",
                new RowMapper.ColToStringRowMapper(),
                new SimplePStmtBinderBuilder().add(Crypter.cryptPassword(password)).toPStmtBinder());
    }
}