/*
 * $Id: VKCLdapServerSerializer.java,v 1.20 2006/07/11 23:40:02 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: VKCLdapServerSerializer.java,v $
 * Revision 1.20  2006/07/11 23:40:02  marbobo
 * + PostgreSQL ist pingelig und erlaubt kein get/setBoolean auf Int-Spalten
 *
 * Revision 1.19  2004/12/17 01:18:33  marbobo
 * + Weitere Umstellungen und Optimierungen bzgl. PreparedStatements
 *
 * Revision 1.18  2004/12/11 18:33:58  marbobo
 * + Restliche Statements auf PreparedStatement umgestellt
 *
 * Revision 1.17  2004/12/07 15:02:10  marbobo
 * + Statement auf PreparedStatement umgestellt
 *
 * Revision 1.16  2004/11/24 13:01:15  lawern
 * Global "conn.setAutoCommit( false );" enfernt, weil überflüssig.
 *
 * Revision 1.15  2004/11/24 09:25:58  lawern
 * Hibernate ist VKC-Geschichte!
 *
 * Revision 1.14  2004/11/18 19:38:24  marbobo
 * + changed order of close-stmt to resultset/connect/session  in finally-blocks
 *
 * Revision 1.13  2004/11/01 15:55:04  vchris
 * + Anpassungen an neues DB-Schema
 *
 * Revision 1.12  2004/10/26 08:10:42  jonyp
 * added mapping_language
 *
 * Revision 1.11  2004/10/25 13:28:48  vchris
 * Nötige Umwandlung von getString() in getInt() an 2 Stellen
 *
 * Revision 1.10  2004/10/25 11:02:26  jonyp
 * added creator/changer methods
 *
 * Revision 1.9  2004/10/22 15:28:21  jonyp
 * *** empty log message ***
 *
 * Revision 1.7  2004/10/21 13:24:07  vchris
 * Update für neue LDAP Funktionalitäten
 *
 * Revision 1.6  2004/10/18 13:18:37  vchris
 * *** empty log message ***
 *
 * Revision 1.5  2004/10/18 00:26:55  vchris
 * *** empty log message ***
 *
 * Revision 1.4  2004/10/15 15:42:26  vchris
 * Erweiterungen
 *
 * Revision 1.3  2004/10/14 15:09:31  jonyp
 * bug fix: changed select statement
 *
 * Revision 1.2  2004/10/14 10:12:30  jonyp
 * *** empty log message ***
 *
 * Revision 1.1  2004/10/07 14:41:12  jonyp
 * first strike
 *
 */

package vkc.ldap.db.serializer;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;

import java.sql.Connection;

import vkc.db.helper.DBHelper;
import vkc.exception.DBException;
import vkc.view.WebShare;
import vkc.ldap.db.entities.VKCLdapServer;

public class VKCLdapServerSerializer {
    private VKCLdapServerSerializer() {
    }

	public final static VKCLdapServer retrieveLdapServer( Integer ldapServerId ) throws DBException {
		Connection conn = null;

		try {
			conn = WebShare.database.getConnection();

			return retrieveLdapServer( ldapServerId, conn );
		} catch ( Exception ex ) {
			throw new DBException( ex );
		} finally {
			DBHelper.close( conn );
		}
	}
    
	public final static VKCLdapServer retrieveLdapServer( Integer ldapServerId, Connection conn ) throws DBException {
	    HashMap ldapServers = getLdapServerInfos( conn, "WHERE ldapServerId = ?", new Object[]{ ldapServerId } );
	    
	    return (VKCLdapServer) ldapServers.get( ldapServerId );
	}

	/**
	 * Speichert einen LDAP Server in der DB ab
	 *
	 * @param ldapServer
	 */
	public static void saveLdapServer( VKCLdapServer ldapServer ) throws DBException {
		Connection conn = null;

		try {
			conn = WebShare.database.getConnection();
			saveLdapServer( ldapServer, conn );
			conn.commit();
		} catch ( Exception ex ) {
			DBHelper.rollBack( conn );
			throw new DBException( ex );
		} finally {
			DBHelper.close( conn );
		}
	}

	/**
	 * Speichert einen LDAP Server in der DB ab
	 *
	 * @param ldapServer
	 * @param conn die Connection
	 */
	public static void saveLdapServer( VKCLdapServer ldapServer, Connection conn )	throws DBException {
		PreparedStatement pStmt = null;

		try {
			String stmt = null;

			if ( ldapServer.getLdapServerId() == null || ldapServer.getLdapServerId().intValue() <= 0 ) {
				ldapServer.setLdapServerId( DBHelper.getNewId( conn, "ldapServers", "ldapServerId" ) );
	
				stmt  = "INSERT INTO ldapServers ( ";
				stmt += "ldapServerUrl, ";
				stmt += "description, ";
				stmt += "authMethod, ";
				stmt += "baseDN, ";
				stmt += "usersBaseRDN, ";
				stmt += "groupsBaseRDN, ";
				stmt += "mapping_loginattr, ";
				stmt += "mapping_email, ";
				stmt += "mapping_userId, ";
				stmt += "mapping_fullname, ";
				stmt += "mapping_language, ";
				stmt += "creatorId, ";
				stmt += "created, ";
				stmt += "lastChangerId, ";
				stmt += "lastChanged, ";
				stmt += "enabled, ";
				stmt += "ldapServerId ) ";
				stmt += " values ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) ";
			} else {
				stmt  = "UPDATE ldapServers SET ";
				stmt += "ldapServerUrl = ?, ";
				stmt += "description = ? , ";
				stmt += "authMethod = ?, ";
				stmt += "baseDN = ?, ";
				stmt += "usersBaseRDN = ?, ";
				stmt += "groupsBaseRDN = ?, ";
				stmt += "mapping_loginattr = ?, ";
				stmt += "mapping_email = ?, ";
				stmt += "mapping_userId = ?, ";
				stmt += "mapping_fullname = ?, ";
				stmt += "mapping_language = ?, ";
				stmt += "creatorId = ?, ";
				stmt += "created = ?, ";
				stmt += "lastChangerId = ?, ";
				stmt += "lastChanged = ?, ";
				stmt += "enabled = ? ";
				stmt += "WHERE ldapServerId = ?";
			}

			pStmt = conn.prepareStatement( stmt );
			pStmt.setString( 1, ldapServer.getLdapServerURL() );
			pStmt.setString( 2, ldapServer.getDescription() );
			pStmt.setString( 3, ldapServer.getAuthMethod() );
			pStmt.setString( 4, ldapServer.getBaseDN() );
			pStmt.setString( 5, ldapServer.getUsersBaseRDN() );
			pStmt.setString( 6, ldapServer.getGroupsBaseRDN() );
			pStmt.setString( 7, ldapServer.getMapping_loginattr() );
			pStmt.setString( 8, ldapServer.getMapping_email() );
			pStmt.setString( 9, ldapServer.getMapping_userid() );
			pStmt.setString( 10, ldapServer.getMapping_fullname() );
			pStmt.setString( 11, ldapServer.getMapping_language() );
			pStmt.setInt( 12, ldapServer.getCreatorId().intValue() );
			pStmt.setTimestamp( 13, ldapServer.getCreated() );
			pStmt.setInt( 14, ldapServer.getLastChangerId().intValue() );
			pStmt.setTimestamp( 15, ldapServer.getLastChanged() );
			pStmt.setInt( 16, ldapServer.isEnabled() ? 1 : 0 );
			pStmt.setInt( 17, ldapServer.getLdapServerId().intValue() );
			pStmt.execute();
		} catch ( Exception ex ) {
			throw new DBException( ex );
		} finally {
			DBHelper.close( pStmt );
		}
	}
	
	public final static void deleteLdapServer( Integer ldapServerId ) throws DBException {
		Connection conn = null;
		PreparedStatement pStmt = null;

		try {
			conn = WebShare.database.getConnection();
			
	        // TODO: more things to do here
			pStmt = conn.prepareStatement( "DELETE FROM ldapServers WHERE ldapServerId = ?" );
			pStmt.setInt( 1, ldapServerId.intValue() );
			pStmt.execute();

			conn.commit();
		} catch ( Exception e ) {
			DBHelper.rollBack( conn );
			throw new DBException( e );
		} finally {
			DBHelper.close( pStmt );
			DBHelper.close( conn );
		}
	}

	public final static void setLdapServerState( Integer ldapServerId, boolean enable ) throws DBException {
		Connection conn = null;
		PreparedStatement pStmt = null;

		try {
			conn = WebShare.database.getConnection();
			
			if ( enable ) {
				pStmt = conn.prepareStatement( "UPDATE ldapServers SET enabled = 1 WHERE ldapServerId = ?" );
				pStmt.setInt( 1, ldapServerId.intValue() );
			} else {
				pStmt = conn.prepareStatement( "UPDATE ldapServers SET enabled = 0 WHERE ldapServerId = ?" );
				pStmt.setInt( 1, ldapServerId.intValue() );
			}
			
	        pStmt.execute();

			conn.commit();
		} catch ( Exception e ) {
			DBHelper.rollBack( conn );
			throw new DBException( e );
		} finally {
			DBHelper.close( pStmt );
			DBHelper.close( conn );
		}
	}
	
	public final static HashMap getAllLdapServers() throws DBException {
		Connection conn = null;

		try {
			conn = WebShare.database.getConnection();
			
			return getAllLdapServers( conn );
		} catch ( Exception ex ) {
			throw new DBException( ex );
		} finally {
			DBHelper.close( conn );
		}
	}
	
	public final static HashMap getAllActiveLdapServers() throws DBException {
		Connection conn = null;
		
		try {
			conn = WebShare.database.getConnection();
			
			return getAllActiveLdapServers( conn );
		} catch ( Exception e ) {
			throw new DBException( e );
		} finally {
			DBHelper.close( conn );
		}
	}
	
	public final static HashMap getAllActiveLdapServers( Connection conn ) throws DBException {
		return getLdapServerInfos( conn, "WHERE enabled = 1 ORDER BY ldapServerId ASC", null );
	}
	
	public final static HashMap getAllLdapServers( Connection conn ) throws DBException {
		return getLdapServerInfos( conn, "ORDER BY ldapServerId ASC", null );
	}
	
	private final static HashMap getLdapServerInfos( Connection conn, String whereCondition, Object[] params )	throws DBException {
		PreparedStatement pStmt = null;
		ResultSet rs = null;		

		HashMap ldapServers = new HashMap();
		
		try {
			pStmt = conn.prepareStatement( "SELECT * FROM ldapServers " + whereCondition );
            DBHelper.setElements( pStmt, params );
			rs = pStmt.executeQuery();
			
			while ( rs.next() ) {
				VKCLdapServer ldapServer = new VKCLdapServer();
				ldapServer.setLdapServerId( new Integer( rs.getInt( "ldapServerId" ) ) );				
				ldapServer.setDescription(rs.getString( "description" ) );
				ldapServer.setLdapServerURL( rs.getString( "ldapServerUrl" ) );
				ldapServer.setAuthMethod( rs.getString( "authMethod" ) );
				ldapServer.setBaseDN( rs.getString( "baseDN" ) );
				ldapServer.setUsersBaseRDN( rs.getString( "usersBaseRDN" ) );
				ldapServer.setGroupsBaseRDN( rs.getString( "groupsBaseRDN" ) );
				ldapServer.setMapping_loginattr( rs.getString( "mapping_loginattr" ) ); 
				ldapServer.setMapping_email( rs.getString( "mapping_email" ) );                 
				ldapServer.setMapping_userid( rs.getString( "mapping_userId" ) ); 
				ldapServer.setMapping_fullname( rs.getString( "mapping_fullname" ) );
				ldapServer.setMapping_language( rs.getString( "mapping_language" ) );
				ldapServer.setCreatorId(new Integer( rs.getInt( "creatorId" )));
				ldapServer.setCreated( rs.getTimestamp( "created" ) );
				ldapServer.setLastChangerId( new Integer( rs.getInt( "lastChangerId" ) ) );
				ldapServer.setLastChanged( rs.getTimestamp( "lastchanged" ) );
				ldapServer.setEnabled( rs.getInt( "enabled" ) != 0 );
				
				ldapServers.put( ldapServer.getLdapServerId(), ldapServer );
			} 

			return ldapServers;
		} catch ( Exception ex ) {
			throw new DBException( ex );
		} finally {
			DBHelper.close( rs );
			DBHelper.close( pStmt );
		}
	}	
}