package isrp.hibernate.model.dao;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import isrp.hibernate.model.businessobject.User;
import isrp.hibernate.model.util.Md5HashCode;

public class UserDao extends GenericDao {

	public UserDao() {
		super(User.class);
	}

	public String getAdministratorEmail() {
		User user = null;
		Query query = session.createQuery("FROM User where role=?").setByte(0,
				new Byte("1"));
		user = (User) query.uniqueResult();
		return user.getEmail();
	}

	@SuppressWarnings("unchecked")
	public List getReviewers() {
		return session.createCriteria(persistedClass).add(
				Restrictions.eq("role", new Byte("3"))).list();
	}

	public User authenticate(String email, String password) {
		password = Md5HashCode.getMd5HashCode(password);
		return (User) session.createCriteria(persistedClass).add(
				Restrictions.eq("email", email)).add(
				Restrictions.eq("password", password)).uniqueResult();
	}

	public User checkIfEmailExistInDB(String email) {
		Query query = session.createQuery("FROM User where email=?").setString(
				0, email);
		return (User) query.uniqueResult();
	}

	@SuppressWarnings("unchecked")
	public List<User> getUsers(String sortColumn) {
		if (sortColumn == null) {
			sortColumn = "firstName";
		}
		return (List<User>) session.createCriteria(persistedClass).addOrder(
				Order.asc(sortColumn)).list();
	}

}
