package gov.va.vinci.dart.rest;

import gov.va.vinci.dart.DartController;
import gov.va.vinci.dart.RequestController;
import gov.va.vinci.dart.biz.Activity;
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.common.exception.ObjectNotFoundException;
import gov.va.vinci.dart.common.json.ErrorView;
import gov.va.vinci.dart.db.util.HibernateSessionManager;
import gov.va.vinci.dart.json.builder.ActivityViewBuilder;
import gov.va.vinci.dart.usr.UserPreferences;

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

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

	@RequestMapping(value = "/requests/{requestId}/activity", method = RequestMethod.GET)
	@ResponseBody
	public Object getActivityByRequestId(@PathVariable final int requestId) throws Exception {
		
		log.debug("getActivityByRequestId"); 
		
		try {
			HibernateSessionManager.start();

			UserPreferences prefs = getUserPreferences();			
			Person person = Person.findById(prefs.getUserId());
			if (person == null) {
				throw new ObjectNotFoundException("Cannot find person with id: " + prefs.getUserId());
			}

			Role.initialize();
		
			if( person.hasRole(Role.SUPER_USER) == false ) {
				return new ErrorView("Error: User does not have permission to perform this action.");
			}
			
			Request request = RequestController.retrieveRequest(requestId);
			if (request == null) {
				return new ErrorView("Error retrieving request: " + requestId);
			}

			Activity activity = request.getActivity();
		
			return new ActivityViewBuilder().build(activity, request, person);
			
		} catch (Exception e) {
			log.error("Error retrieving activity data.", e);
			HibernateSessionManager.rollback();
			throw e;
		} finally {
			HibernateSessionManager.close();
		}
	}
	
}
