package org.sistema.springmvc.forms.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.sistema.springmvc.forms.models.User;
import org.springframework.transaction.annotation.Transactional;

/**
 * Implementation of an specific UserDAO
 * 
 * @author Eugenia Pérez Martínez
 * @email eugenia_perez@cuatrovientos.org
 *
 */

public class UserDAO extends GenericDAO<User> {

	/**
	 * Selects all users types by login
	 * 
	 * @return List of users
	 */
	@Transactional(readOnly = true)
	public List<User> selectByLogin(String login) {

		List<User> users = null;

		Query query = getSession().createQuery(
				"from User u where u.login LIKE :login");
		query.setParameter("login", "%" + login + "%");
		users = query.list();

		return users;
	}
	
	/**
	 * Selects all users after searching by criteria
	 * 
	 * @return List of users
	 */
	@Transactional(readOnly = true)
	public List<User> selectPaginated(Integer number, boolean isAscending) {

		List<User> users = null;
		String order = isAscending?"asc":"desc";
		try {
			Query query = getSession()
					.createQuery("from User s ORDER BY s.login " + order);
				    query.setMaxResults(number);
				    users = query.list();
		} catch (HibernateException he) {
			handleException(he);
		}

		return users;
	}
}
