package gov.va.vinci.dart.rest;

import gov.va.vinci.dart.DartController;
import gov.va.vinci.dart.biz.Comment;
import gov.va.vinci.dart.biz.NestableComment;
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.CommentListViewBuilder;
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 CommentResource extends DartController {

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

	@RequestMapping(value = "/requests/{requestId}/comments", method = RequestMethod.GET)
	@ResponseBody
	public Object listCommentsByRequest(@PathVariable int requestId) throws Exception {
		log.debug("list comments 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<NestableComment> commentList = Comment.listByRequestId(requestId);
			return new CommentListViewBuilder().build(commentList);		
			
		} catch (Exception e) {
			log.error("Error retrieving comments.", e);
			HibernateSessionManager.rollback();
			throw e;
		} finally {
			HibernateSessionManager.close();
		}
	}
}
