/*
 * Copyright 
 *   2005 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 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.basic.mysql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import fr.gouv.finances.cp.xemelios.Splash;
import fr.gouv.finances.cp.xemelios.auth.AbstractAuthenticationManager;
import fr.gouv.finances.cp.xemelios.auth.AuthChecker;
import fr.gouv.finances.cp.xemelios.auth.AuthProvider;
import fr.gouv.finances.cp.xemelios.auth.AuthenticationCancelationException;
import fr.gouv.finances.cp.xemelios.auth.AuthenticationConfigurationException;
import fr.gouv.finances.cp.xemelios.auth.XemeliosUser;
import fr.gouv.finances.cp.xemelios.auth.basic.AskPassword;
import fr.gouv.finances.cp.xemelios.auth.basic.BasicUser;
import fr.gouv.finances.cp.xemelios.auth.basic.NewPassword;
import fr.gouv.finances.cp.xemelios.common.Crypter;
import fr.gouv.finances.cp.xemelios.data.DataAccessException;
import fr.gouv.finances.cp.xemelios.data.DataConfigurationException;
import fr.gouv.finances.cp.xemelios.data.DataImpl;
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 Manager extends AbstractAuthenticationManager implements AuthChecker {
	private AuthProvider provider = null;

	public Manager(MainWindow mw) throws AuthenticationConfigurationException, AuthenticationCancelationException {
		super();
		setMainWindow(mw);
		try {
			if(! (DataLayerManager.getImplementation() instanceof MySqlDataLayer))
				throw new AuthenticationConfigurationException(getAuthenticationManagerName()+" can run only with mysql data layer");
			Connection con = null;
			MySqlDataLayer dataLayer = null;
			PreparedStatement ps = null;
			try {
				dataLayer = (MySqlDataLayer)DataLayerManager.getImplementation();
				con = dataLayer.getConnection();
				String sql = "CREATE TABLE IF NOT EXISTS BASIC_USERS (LOGIN VARCHAR(24) NOT NULL, PASSWORD VARCHAR(128) NOT NULL, ACCESS INT)";
				con.createStatement().executeUpdate(sql);
				ResultSet rs = con.createStatement().executeQuery("SELECT COUNT(*) FROM BASIC_USERS");
				if(rs.next()) {
					int size = rs.getInt(1);
					if(size==0) {
						if(getMainWindow().getStartListener() instanceof Splash) {
							Splash splash = (Splash)getMainWindow().getStartListener();
							splash.setAlwaysOnTop(false);
							splash.setVisible(false);
						}
						NewPassword np = new NewPassword(getMainWindow());
						boolean bRet = np.run();
						if(getMainWindow().getStartListener() instanceof Splash) {
							Splash splash = (Splash)getMainWindow().getStartListener();
							splash.setVisible(true);
							splash.setAlwaysOnTop(true);
						}
						if(bRet) {
							String[] passwords = np.getNewPassword();
							sql = "INSERT INTO BASIC_USERS(LOGIN,PASSWORD,ACCESS) VALUES (?,?,?)";
							ps = con.prepareStatement(sql);
							ps.setString(1,"anonymous");
							ps.setString(2,Crypter.cryptPassword(passwords[DataImpl.READ_ONLY_PASS]));
							ps.setInt(3,
									XemeliosUser.ROLE_CONNECT |
									XemeliosUser.ROLE_SEARCH |
									XemeliosUser.ROLE_BROWSE |
									XemeliosUser.ROLE_EXPORT
									);
							ps.executeUpdate();
							ps.setString(1,"admin");
							ps.setString(2,Crypter.cryptPassword(passwords[DataImpl.READ_WRITE_PASS]));
							ps.setInt(3,
									XemeliosUser.ROLE_CONNECT |
									XemeliosUser.ROLE_IMPORT |
									XemeliosUser.ROLE_CLEAN |
									XemeliosUser.ROLE_SEARCH |
									XemeliosUser.ROLE_BROWSE |
									XemeliosUser.ROLE_EXPORT
									);
							ps.executeUpdate();
						} else {
							throw new AuthenticationCancelationException("Action interrompue");
						}
					}
				}
			} catch(SQLException sqlEx) {
				throw new AuthenticationConfigurationException(sqlEx);
			} finally {
				if(ps!=null) try { ps.close(); } catch(Throwable t) {}
				if(con!=null) dataLayer.releaseConnection(con);
			}
		} catch(DataConfigurationException dcEx) {
			// ignore it, it has already been thrown before
		}
	}

	public AuthChecker getChecker() {
		return this;
	}

	public AuthProvider getProvider() {
		if(provider==null) provider = new AskPassword(getMainWindow());
		return provider;
	}

	public String getAuthenticationManagerName() {
		return "MySql-based basic authenticator";
	}

	public boolean authenticate(XemeliosUser user) throws DataAccessException, AuthenticationConfigurationException {
		BasicUser bu = null;
		if(user instanceof BasicUser) {
			bu = (BasicUser)user;
		} else {
			throw new AuthenticationConfigurationException("can only authenticate BasicUser");
		}
		Connection con = null;
		MySqlDataLayer dataLayer = null;
		PreparedStatement ps = null;
		try {
			dataLayer = (MySqlDataLayer)DataLayerManager.getImplementation();
			con = dataLayer.getConnection();
			String sql = "SELECT LOGIN,ACCESS FROM BASIC_USERS WHERE PASSWORD=?";
			ps = con.prepareStatement(sql);
			ps.setString(1,bu.getCryptedPassword());
			ResultSet rs = ps.executeQuery();
			if(rs.next()) {
				bu.setId(rs.getString(1));
				bu.setAuth(rs.getInt(2));
				rs.close();
			}
		} catch(DataConfigurationException dcEx) {
			throw new AuthenticationConfigurationException(dcEx);
		} catch(SQLException sqlEx) {
			throw new DataAccessException(sqlEx);
		} finally {
			if(ps!=null) try { ps.close(); } catch(Throwable t) {}
			if(con!=null) dataLayer.releaseConnection(con);
		}
		return user.isAllowedTo(null,XemeliosUser.ROLE_CONNECT);
	}
}
