/* ===================================================================
 * UserDaoImpl.java
 * 
 * Created Sep 29, 2004 1:17:04 PM
 * 
 * Copyright (c) 2004 Matt Magoffin (spamsqr@msqr.us)
 * 
 * This program 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.
 * 
 * This program 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 this program; if not, write to the Free Software 
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 
 * 02111-1307 USA
 * ===================================================================
 * $Id: UserDaoImpl.java 39 2009-05-06 03:30:47Z msqr $
 * ===================================================================
 */

package magoffin.matt.ieat.dao.hbm;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import magoffin.matt.dao.hbm.GenericHibernateDao;
import magoffin.matt.ieat.dao.UserDao;
import magoffin.matt.ieat.domain.User;
import magoffin.matt.ieat.domain.impl.UserImpl;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.orm.hibernate3.HibernateTemplate;

/**
 * UserDao implementation using Hibernate.
 * 
 * @author Matt Magoffin (spamsqr@msqr.us)
 * @version $Revision: 39 $ $Date: 2009-05-06 15:30:47 +1200 (Wed, 06 May 2009) $
 */
public class UserDaoImpl extends GenericHibernateDao<User,Integer> implements UserDao {

	/** The query to find a user by login. */
	public static final String FIND_BY_LOGIN = "UserByLogin";
	
	/** The query to find a user by email address. */
	public static final String FIND_BY_EMAIL = "UserByEmail";
	
	/** The query to find all users with a particular access level. */
	public static final String FIND_FOR_ACCESS_LEVEL = "UserForAccessLevel";
	
	/** The query to find stale user registrations. */
	public static final String FIND_STALE_REGISTRATIONS = "UsersStaleRegistration";
	
	private JdbcTemplate jdbcTemplate;
	private String sqlIndexAll;

	/**
	 * Default constructor.
	 */
	public UserDaoImpl() {
		super(UserImpl.class);
	}

	/**
	 * Method to call after all dependency injection has occured.
	 */
	public void init() {
		if ( jdbcTemplate == null ) {
			throw new RuntimeException("jdbcTemplate not configured");
		}
		if ( sqlIndexAll == null ) {
			throw new RuntimeException("sqlIndexAll not configured");
		}
	}

	@Override
	protected Integer getPrimaryKey(User domainObject) {
		if ( domainObject == null ) return null;
		return domainObject.getUserId();
	}
	
	/* (non-Javadoc)
	 * @see magoffin.matt.ieat.dao.UserDao#getUsersForAccessLevel(int)
	 */
	public List<User> getUsersForAccessLevel(int accessLevel) {
		return findByNamedQuery(FIND_FOR_ACCESS_LEVEL, new Object[] {accessLevel});
	}
	
	/* (non-Javadoc)
	 * @see magoffin.matt.ieat.dao.UserDao#getUser(java.lang.String)
	 */
	public User getUser(String login) {
		List<User> results = findByNamedQuery(FIND_BY_LOGIN, new Object[] {login});
		if ( results.size() < 1 ) {
			return null;
		}
		return results.get(0);
	}

	/* (non-Javadoc)
	 * @see magoffin.matt.ieat.dao.UserDao#getUserByEmail(java.lang.String)
	 */
	public User getUserByEmail(String email) {
		List<User> results = findByNamedQuery(FIND_BY_EMAIL, new Object[] {email});
		if ( results.size() < 1 ) {
			return null;
		}
		return results.get(0);
	}
	
	/* (non-Javadoc)
	 * @see magoffin.matt.ieat.dao.UserDao#index(magoffin.matt.ieat.dao.UserDao.UserIndexCallback)
	 */
	public void index(final UserIndexCallback callback) {
		if ( log.isDebugEnabled() ) {
			log.debug("Executing SQL for index all users: " +sqlIndexAll);
		}
		final UserIndexCallbackDataImpl callbackData = new UserIndexCallbackDataImpl();
		jdbcTemplate.query(sqlIndexAll, 
				new RowCallbackHandler() {
					private ResultSet myRs;
					public void processRow(ResultSet rs) throws SQLException {
						if ( myRs == null ) {
							myRs = rs;
						}
						callbackData.userId = new Integer(rs.getInt(1));
						callbackData.name = rs.getString(2);
						callbackData.login = rs.getString(3);
						callbackData.email = rs.getString(4);
						callbackData.accessLevel = (Integer)rs.getObject(5);
						Date d = rs.getDate(6);
						if ( d != null ) {
							Calendar c = Calendar.getInstance();
							c.setTime(d);
							callbackData.createdDate = c;
						}
						d = rs.getDate(7);
						if ( d != null ) {
							Calendar c = Calendar.getInstance();
							c.setTime(d);
							callbackData.lastLoginDate = c;
						}
						callback.handle(callbackData);
					}
				}
				);
	}
	
	private static class UserIndexCallbackDataImpl implements UserIndexCallbackData {
		private Integer userId;
		private String name;
		private String login;
		private String email;
		private Integer accessLevel;
		private Calendar createdDate;
		private Calendar lastLoginDate;
		
		public String getName() {
			return name;
		}
		public Integer getUserId() {
			return userId;
		}
		public String getLogin() {
			return login;
		}
		public Integer getAccessLevel() {
			return accessLevel;
		}
		public Calendar getCreatedDate() {
			return createdDate;
		}
		public String getEmail() {
			return email;
		}
		public Calendar getLastLoginDate() {
			return lastLoginDate;
		}
	}
	
	/* (non-Javadoc)
	 * @see magoffin.matt.ieat.dao.UserDao#removeStaleUserRegistrations()
	 */
	public int removeStaleUserRegistrations() {
		HibernateTemplate template = getHibernateTemplate();
		List<?> staleList = template.findByNamedQuery(FIND_STALE_REGISTRATIONS);
		int result = staleList.size();
		template.deleteAll(staleList);
		return result;
	}
	
	/**
	 * @return the jdbcTemplate
	 */
	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}
	
	/**
	 * @param jdbcTemplate the jdbcTemplate to set
	 */
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	
	/**
	 * @return the sqlIndexAll
	 */
	public String getSqlIndexAll() {
		return sqlIndexAll;
	}
	
	/**
	 * @param sqlIndexAll the sqlIndexAll to set
	 */
	public void setSqlIndexAll(String sqlIndexAll) {
		this.sqlIndexAll = sqlIndexAll;
	}
	
}
