package de.thomasjacob.improve.logic.user;

import de.thomasjacob.improve.logic.project.Project;
import de.thomasjacob.webcore.TechnicalException;
import de.thomasjacob.webcore.logic.Dao;

import java.util.List;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Query;


public class UserDao extends Dao
{
	public List findEnabledDevelopers() throws TechnicalException
	{
		try
		{
			return getSession(false).getNamedQuery("UserDao.findEnabledDevelopers").list();
		}
		catch (HibernateException exception)
		{
			throw new TechnicalException("hibernate operation failed", exception);
		}
	}

	public List findEnabledManagers(Project project) throws TechnicalException
	{
		try
		{
			Query query = getSession(false).getNamedQuery("UserDao.findEnabledManagers");
			query.setEntity("project", project);
			return query.list();
		}
		catch (HibernateException exception)
		{
			throw new TechnicalException("hibernate operation failed", exception);
		}
	}

	public List findUsers() throws TechnicalException
	{
		try
		{
			return getSession(false).getNamedQuery("UserDao.findUsers").list();
		}
		catch (HibernateException exception)
		{
			throw new TechnicalException("hibernate operation failed", exception);
		}
	}

	public User getUserById(int userId) throws TechnicalException
	{
		return (User) getModelById(User.class, userId);
	}

	public User getValidUser(String name, String password) throws TechnicalException
	{
		List users;
		try
		{
			Query query = getSession(false).getNamedQuery("UserDao.getValidUser");
			query.setString("name", name);
			query.setString("password", password);
			users = query.list();
		}
		catch (HibernateException exception)
		{
			throw new TechnicalException("hibernate operation failed", exception);
		}

		if (users.size() != 1)
		{
			return null;
		}

		return (User) users.iterator().next();
	}

	public boolean isUserNameExisting(String name, int otherId) throws TechnicalException
	{
		List users;
		try
		{
			Query query = getSession(false).getNamedQuery("UserDao.isUserNameExisting");
			query.setString("name", name);
			users = query.list();
		}
		catch (HibernateException exception)
		{
			throw new TechnicalException("hibernate operation failed", exception);
		}

		if (users.isEmpty())
		{
			return false;
		}
		else if (users.size() > 1)
		{
			throw new TechnicalException("Duplicate name in user table: " + name);
		}

		User user = (User) users.iterator().next();
		if (otherId == 0)
		{
			return true;
		}
		else
		{
			return user.getId() != otherId;
		}
	}
}