package gov.va.vinci.dart.rest;

import gov.va.vinci.dart.common.json.ErrorView;
import gov.va.vinci.dart.DartController;
import gov.va.vinci.dart.biz.GroupTask;
import gov.va.vinci.dart.biz.Person;
import gov.va.vinci.dart.biz.Request;
import gov.va.vinci.dart.biz.Role;
import gov.va.vinci.dart.biz.Task;
import gov.va.vinci.dart.db.util.HibernateSessionManager;
import gov.va.vinci.dart.json.TaskListView;
import gov.va.vinci.dart.json.TaskView;
import gov.va.vinci.dart.json.builder.TaskViewBuilder;
import gov.va.vinci.dart.usr.UserPreferences;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class TaskResource extends DartController {

	private static Log log = LogFactory.getLog(TaskResource.class);
	
	@RequestMapping(value = "/groups/{groupId}/tasks", method = RequestMethod.GET)
	@ResponseBody
	public Object getTasksByGroupId(@PathVariable final int groupId) throws Exception {
		
		log.debug("getTasksByGroupId"); 
		
		try {
			HibernateSessionManager.start();
			
			UserPreferences prefs = getUserPreferences();
			
			Person person = Person.findById(prefs.getUserId());
			
			Role.initialize();
			
			if( person != null && person.hasRole(Role.SUPER_USER) == false ) {
				return new ErrorView("Error: User does not have permission to perform this action.");
			}

			ArrayList<Integer> distinctRequestsIdList = new ArrayList<Integer>();

			TaskListView result = new TaskListView();
			
			int requestId;
			List<GroupTask>glist = GroupTask.listOpenByOwner(groupId);	//get the open tasks for this group

			for (Task task : glist) {
				if (task.getCompletedOn() == null) {
					Request request = task.getRequest();
	
					if (request == null) {
						log.error("Error : null request found for task id " + task.getId());
					} 
					else {
						requestId = request.getId();
						
						if (distinctRequestsIdList.contains(requestId) == false) {
							
							TaskView view = new TaskViewBuilder().build(request, task, true);
							result.getTasks().add(view);	//group tasks are for reviewers (could base this on the GroupTask type)
							
							distinctRequestsIdList.add(requestId);
						}
					}
				}
			}
			
			return result;
			
		} catch (Exception e) {
			log.error("Error retrieving group task data.", e);
			HibernateSessionManager.rollback();
			throw e;
		} finally {
			HibernateSessionManager.close();
		}
	}

}
