package gov.va.vinci.dart.rest;

import gov.va.vinci.dart.DartController;
import gov.va.vinci.dart.biz.Event;
import gov.va.vinci.dart.biz.EventSummary;
import gov.va.vinci.dart.biz.Person;
import gov.va.vinci.dart.biz.Role;
import gov.va.vinci.dart.common.json.ErrorView;
import gov.va.vinci.dart.db.util.HibernateSessionManager;
import gov.va.vinci.dart.json.builder.EventHistoryViewBuilder;
import gov.va.vinci.dart.json.builder.EventRequestViewBuilder;
import gov.va.vinci.dart.usr.UserPreferences;

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 EventResource extends DartController {


	private static Log log = LogFactory.getLog(CommentResource.class);

	@RequestMapping(value = "/requests/{requestId}/events", method = RequestMethod.GET)
	@ResponseBody
	public Object listEventsByRequest(@PathVariable int requestId) throws Exception {
		log.debug("list events for request " + requestId);
 
		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.");
			}

			List<EventSummary> eventSummaryList = Event.listSummaryByRequestId(requestId);

			return new EventRequestViewBuilder().build(eventSummaryList);
		} catch (Exception e) {
			log.error("Error retrieving request events.", e);
			HibernateSessionManager.rollback();
			throw e;
		} finally {
			HibernateSessionManager.close();
		}
	}
	
	@RequestMapping(value = "/activities/{activityId}/events", method = RequestMethod.GET)
	@ResponseBody
	public Object listEventsByActivity(@PathVariable int activityId) throws Exception {
		log.debug("list events for activity " + activityId);
 
		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.");
			}

			List<EventSummary> eventSummaryList = Event.listSummaryByActivityId(activityId);

			return new EventHistoryViewBuilder().build(eventSummaryList);
		} catch (Exception e) {
			log.error("Error retrieving activity events.", e);
			HibernateSessionManager.rollback();
			throw e;
		} finally {
			HibernateSessionManager.close();
		}
	}
}
