package gov.va.vinci.dart;

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.LoginSuccessView;
import gov.va.vinci.dart.json.LoginView;
import gov.va.vinci.dart.json.atom.AtomLinkFactory;
import gov.va.vinci.dart.usr.UserPreferences;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginController extends DartController {
	private static Log log = LogFactory.getLog(LoginController.class);
	
	@Autowired 
	private AtomLinkFactory linkFactory;
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public Object loginUser(@RequestBody @Valid final LoginView request, final HttpServletRequest httpRequest) {

		log.debug("loginUser");
		
		linkFactory.setURIBase(httpRequest.getRequestURL().toString());

		try {
			HibernateSessionManager.start();

			UserPreferences prefs = getUserPreferences();

			// authentication is called by Spring Security before this handler is called.
//			userManager.login(request.getUsername(), request.getPassword());
			
			Person person = Person.findById(prefs.getUserId());

			log.info("User " + prefs.getUserLoginId() + " logged in.");

			Role.initialize();
			
			if (person.hasRole(Role.REVIEWER)) {
				log.debug("User " + request.getUsername() + " is a Dart request reviewer.");
			}
			
			// check if we need to copy the person's full name from AD into our local database
			if ((person.getFullName() == null || person.getFullName().length() < 1) &&
					(prefs.getUserFullName() != null && prefs.getUserFullName().length() > 0) ) {
				person.setFullName(prefs.getUserFullName());
			}
		}
		catch (Exception e) {
			log.error("Error in user login.", e);
			HibernateSessionManager.rollback();
			return new ErrorView("Error");
		}
		finally {	
			HibernateSessionManager.close();
		}
		
		LoginSuccessView result = new LoginSuccessView("OK");
		
		// can send a different start page here based on role
		result.setNextPage("./dashboard.html");
		
		return result;
	}
}
