package gov.va.vinci.dart.rest;

import gov.va.vinci.dart.DartController;
import gov.va.vinci.dart.biz.DocumentTemplate;
import gov.va.vinci.dart.biz.Person;
import gov.va.vinci.dart.biz.Request;
import gov.va.vinci.dart.biz.RequestLocationDocumentSummary;
import gov.va.vinci.dart.biz.RequestParticipantDocumentSummary;
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.DocumentListView;
import gov.va.vinci.dart.json.DocumentTemplateListView;
import gov.va.vinci.dart.json.RequestLocationDocumentListView;
import gov.va.vinci.dart.json.RequestParticipantDocumentListView;
import gov.va.vinci.dart.json.builder.DocumentTemplateListViewBuilder;
import gov.va.vinci.dart.json.builder.RequestLocationDocumentListViewBuilder;
import gov.va.vinci.dart.json.builder.RequestParticipantDocumentListViewBuilder;
import gov.va.vinci.dart.usr.UserPreferences;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
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 DocumentResource extends DartController {

	private static Log log = LogFactory.getLog(DocumentResource.class);
	
	@RequestMapping(value = "/requests/{requestId}/documents2", method = RequestMethod.GET)
	@ResponseBody
	public Object listDocuments2(@PathVariable int requestId, final HttpServletRequest request) throws Exception {

		log.debug("listDocuments");

		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.");
			}
			
			DocumentListView result = new DocumentListView();
			
			Object locationListView = listDocumentsLocations2(requestId, request);
			if( locationListView instanceof ErrorView ) {
				return locationListView;
			}
			result.getLocations().clear();
			result.getLocations().addAll(((RequestLocationDocumentListView)locationListView).getLocations());
			
			Object participantListView = listDocumentsParticipants2(requestId, request);
			if( participantListView instanceof ErrorView ) {
				return participantListView;
			}
			result.getParticipants().clear();
			result.getParticipants().addAll(((RequestParticipantDocumentListView)participantListView).getParticipants());
			
			return result;
		} catch (Exception e) {
			log.error("Error loading document list", e);
			HibernateSessionManager.rollback();
			throw e;
		} finally {
			HibernateSessionManager.close();
		}
	}
	
	// can also pass query param "reviewer="vhausername" to get all review notes from specified reviewer.
	@RequestMapping(value = "/requests/{requestId}/documents/locations2", method = RequestMethod.GET)
	@ResponseBody
	public Object listDocumentsLocations2(@PathVariable int requestId, final HttpServletRequest request) throws Exception {

		log.debug("listDocument Locations");

		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.");
			}
			
			String reviewerName;
			
			String queryString = request.getQueryString();
			RestQuery q = new RestQuery(queryString);
			String term = q.getTerm("reviewer");
			
			if (q != null && q.isEmpty() == false && StringUtils.isEmpty(term) == false) {
				reviewerName = term;
			}
			else {
				Person reviewer = Person.findById(prefs.getUserId());
				reviewerName = reviewer.getName();
			}
			
			List<RequestLocationDocumentSummary> summaryList = Request.listRequestLocationDocumentSummaryByReviewer(requestId, reviewerName);
			
			return new RequestLocationDocumentListViewBuilder().build(summaryList);
			
		} catch (Exception e) {
			log.error("Error loading document list", e);
			HibernateSessionManager.rollback();
			throw e;
		} finally {
			HibernateSessionManager.close();
		}
	}
	
	// can also pass query param "reviewer="vhausername" to get all review notes from specified reviewer.
	@RequestMapping(value = "/requests/{requestId}/documents/participants2", method = RequestMethod.GET)
	@ResponseBody
	public Object listDocumentsParticipants2(@PathVariable int requestId, final HttpServletRequest request) throws Exception {

		log.debug("listDocument Participants");

		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.");
			}

			String reviewerName;
			
			String queryString = request.getQueryString();
			RestQuery q = new RestQuery(queryString);
			String term = q.getTerm("reviewer");
			
			if (q != null && q.isEmpty() == false && StringUtils.isEmpty(term) == false) {
				reviewerName = term;
			}
			else {
				Person reviewer = Person.findById(prefs.getUserId());
				reviewerName = reviewer.getName();
			}
			
			List<RequestParticipantDocumentSummary> summaryList = Request.listRequestParticipantDocumentSummaryByReviewer(requestId, reviewerName);
			
			return new RequestParticipantDocumentListViewBuilder().build(summaryList);
			
		} catch (Exception e) {
			log.error("Error loading document list", e);
			HibernateSessionManager.rollback();
			throw e;
		} finally {
			HibernateSessionManager.close();
		}
	}
	
//	@RequestMapping(value = "/listAdminDocumentsByRequest", method = RequestMethod.POST)
	
//	@RequestMapping(value = "/listAdminDocumentsForAllGroups", method = RequestMethod.POST)
	
//	@RequestMapping(value = "/listAdminReviewDocumentsForAllGroups", method = RequestMethod.POST)
	
	@RequestMapping(value = "/DocumentTemplates", method = RequestMethod.GET)
	@ResponseBody
	public Object listDocumentTemplates(final HttpServletRequest request) throws Exception {

		log.debug("listDocumentTemplates");
		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<DocumentTemplate> templateList = DocumentTemplate.listAll();
			DocumentTemplateListView result = new DocumentTemplateListViewBuilder().build(templateList);
			
			return result;
		} catch (Exception e) {
			log.error("Error loading document template list.", e);
			HibernateSessionManager.rollback();
			throw e;
		} finally {
			HibernateSessionManager.close();
		}	
	}

}
