package de.thomasjacob.improve.logic.project;

import de.thomasjacob.improve.logic.user.User;
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 ProjectDao extends Dao
{
	public List findEnabledProjects() throws TechnicalException
	{
		try
		{
			return getSession(false).getNamedQuery("ProjectDao.findEnabledProjects").list();
		}
		catch (HibernateException exception)
		{
			throw new TechnicalException("hibernate operation failed", exception);
		}
	}

	public List findEnabledManagedProjects(User user) throws TechnicalException
	{
		try
		{
			Query query = getSession(false).getNamedQuery("ProjectDao.findEnabledManagedProjects");
			query.setEntity("user", user);
			return query.list();
		}
		catch (HibernateException exception)
		{
			throw new TechnicalException("hibernate operation failed", exception);
		}
	}

	public List findEnabledReportableProjects(User user) throws TechnicalException
	{
		try
		{
			Query query = getSession(false).getNamedQuery("ProjectDao.findEnabledReportableProjects");
			query.setEntity("user", user);
			return query.list();
		}
		catch (HibernateException exception)
		{
			throw new TechnicalException("hibernate operation failed", exception);
		}
	}

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

	public Project getProjectById(int projectId) throws TechnicalException
	{
		return (Project) getModelById(Project.class, projectId);
	}

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

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

		Project project = (Project) projects.iterator().next();
		if (otherId == 0)
		{
			return true;
		}
		else
		{
			return project.getId() != otherId;
		}
	}
}