/*
 * 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.dgfip.xemelios.auth.impl.basic;

import fr.gouv.finances.dgfip.xemelios.auth.AuthEngine;
import fr.gouv.finances.dgfip.xemelios.auth.AuthEngine.Helper;
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;
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.ResultSet;
import java.sql.SQLException;

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

    public OldBasicAuthEngineImpl() {
        Connection connection = null;
        try {
            connection = PoolManager.getInstance().getConnection();
            JdbcUtils.executeUpdate(connection,
                    "CREATE TABLE IF NOT EXISTS BASIC_USERS (LOGIN VARCHAR(24) NOT NULL, PASSWORD VARCHAR(128) NOT NULL, ACCESS INT)");
            connection.setAutoCommit(false);
            createAccountIfNeeded(connection);
            connection.commit();
        } 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 BASIC_USERS", new RowMapper.ColToLongRowMapper());
        if (userCount == 0) {
            BasicAuthEngineConfiguationDialog confDialog = new BasicAuthEngineConfiguationDialog(null);
            if (confDialog.run()) {
                SimplePStmtBinderBuilder binderBuilder = new SimplePStmtBinderBuilder();
                binderBuilder.add("anonymous");
                binderBuilder.add(Crypter.cryptPassword(confDialog.getNewPassword()[DataImpl.READ_ONLY_PASS]));
                binderBuilder.add(XemeliosUser.ROLE_CONNECT_BIT | XemeliosUser.ROLE_SEARCH_BIT | XemeliosUser.ROLE_BROWSE_BIT | XemeliosUser.ROLE_EXPORT_BIT);
                JdbcUtils.executeUpdate(connection,
                        "INSERT INTO BASIC_USERS(LOGIN,PASSWORD,ACCESS) VALUES (?,?,?)",
                        binderBuilder.toPStmtBinder());
                binderBuilder = new SimplePStmtBinderBuilder();
                binderBuilder.add("admin");
                binderBuilder.add(Crypter.cryptPassword(confDialog.getNewPassword()[DataImpl.READ_WRITE_PASS]));
                binderBuilder.add(XemeliosUser.ROLE_CONNECT_BIT | XemeliosUser.ROLE_IMPORT_BIT | XemeliosUser.ROLE_CLEAN_BIT | XemeliosUser.ROLE_SEARCH_BIT | XemeliosUser.ROLE_BROWSE_BIT | XemeliosUser.ROLE_EXPORT_BIT);
                JdbcUtils.executeUpdate(connection,
                        "INSERT INTO BASIC_USERS(LOGIN,PASSWORD,ACCESS) VALUES (?,?,?)",
                        binderBuilder.toPStmtBinder());
            } else {
                System.exit(0); // TODO : voir si c'est raisonnable
            }
        }
    }

    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 sql = "SELECT LOGIN, ACCESS FROM BASIC_USERS WHERE PASSWORD = ?";
            PStmtBinder binder = new SimplePStmtBinderBuilder().add(Crypter.cryptPassword(password)).toPStmtBinder();
            return (XemeliosUser) JdbcUtils.queryObject(connection, sql, new RowMapper() {

                public Object map(ResultSet rs) throws SQLException {
                    return new SimpleXemeliosUserImpl(rs.getString("LOGIN"), rs.getString("LOGIN"),
                            false, Helper.rolesFromInt(rs.getInt("ACCESS")), true, null, true, null);
                }
            }, binder);
        } catch (SQLException sqle) {
            throw new SQLRuntimeException(sqle);
        } finally {
            PoolManager.getInstance().releaseConnection(connection);
        }
    }
}
