package com.example.beer.dao;

import javax.ejb.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import com.example.beer.model.Project;
import com.example.beer.model.Task;
import com.example.beer.model.Task.TaskStatus;
import com.example.beer.model.User;

@Singleton
public class TaskDAO {
	@PersistenceContext
	private EntityManager em;
	
	private ProjectDAO projectDAO;
	private TaskDAO taskDAO;
	private UserDAO userDAO;
	
	public boolean addTask(String name, String description, User user) {
		Task foundTask = findTaskByName(name);
		
		if (foundTask == null) {
			em.persist(foundTask);
			return true;
		}
		
		return false;
	}
	
	public Task findTaskByName(String name) {
		String idQueryText = "SELECT t FROM Task t WHERE t.name = :name";
		TypedQuery<Task> taskQuery = em.createQuery(idQueryText, Task.class);
		taskQuery.setParameter("name", name);
		
		Task task = null;
		try {
            task = taskQuery.getSingleResult();
		} catch (Exception e) {
			return null;
		}
		
		return task;
	}

	public Task getTaskById(int id) {
		String idQueryText = "SELECT t FROM Task t WHERE t.id = :id";
		TypedQuery<Task> taskQuery = em.createQuery(idQueryText, Task.class);
		taskQuery.setParameter("id", id);

		Task task = null;
		try {
            task = taskQuery.getSingleResult();
		} catch (Exception e) {
			return null;
		}
		
		return task;
	}
	
	public boolean addToProject(Project project, Task task) {
		if (projectDAO.findProjectById(project.getId()) != null &&
			taskDAO.getTaskById(task.getId()) != null) {
			
			project.addTask(task);
			task.setProject(project);
			em.persist(project);
			em.persist(task);
			
			return true;
		} else {
			return false;
		}
	}

	public boolean assignUser(Task task, User user) {
		if (taskDAO.findTaskByName(task.getName()) == null) {
			return false;
		}
		
		if (userDAO.getUserByName(user.getName()) == null) {
			return false;
		}
		
		task.assignUser(user);
		em.persist(task);
		em.persist(user);
		return true;
	}

	public boolean changeStatus(Task task, TaskStatus status) {
		if (taskDAO.findTaskByName(task.getName()) == null) {
			return false;
		}
		
		task.setTaskStatus(status);
		em.persist(task);
		return true;
	}
}

@@ -52,16 +52,44 @@
 gleton;%0A
+import javax.inject.Inject;%0A
 import j
@@ -446,16 +446,25 @@
 r em;%0A%09%0A
+%09@Inject%0A
 %09private
@@ -491,33 +491,17 @@
 AO;%0A
-%09private TaskDAO taskDAO;
+%0A%09@Inject
 %0A%09pr
@@ -1582,24 +1582,16 @@
 l &&%0A%09%09%09
-taskDAO.
 getTaskB
@@ -1832,32 +1832,24 @@
 er) %7B%0A%09%09if (
-taskDAO.
 findTaskByNa
@@ -2136,16 +2136,8 @@
 if (
-taskDAO.
 find

Remove TaskDAO object from TaskDAO and @Inject the other DAO's