package com.qmth.qrzk.security;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.qmth.qrzk.repository.constants.WebConstants;
import com.qmth.qrzk.repository.user.model.Role;
import com.qmth.qrzk.repository.user.model.User;
import com.qmth.qrzk.repository.user.service.IRoleService;
import com.qmth.qrzk.repository.user.service.IUserService;
import com.qmth.qrzk.repository.utils.General;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

	@Autowired
	@Qualifier("userServiceImpl")
	private IUserService userService;
	
	@Autowired
	@Qualifier("roleServiceImpl")
	private IRoleService roleService;
	
	
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication arg2) throws IOException,
			ServletException {
		initSessionData(request.getSession());
		
		User user = (User) request.getSession().getAttribute(WebConstants.WEB_SESSION_USER);
		user.setLastLoginDate(new Date());
		userService.updateLastLoginDate(user);
		
		request.getSession().setAttribute("headMenu", "user");
        request.getSession().setAttribute("subMenu", "info");
		
		@SuppressWarnings("unchecked")
		List<Role> roles = (List<Role>)request.getSession().getAttribute(WebConstants.WEB_SESSION_ALLROLES);
		if(roles.size() > 1)
			response.sendRedirect(General.getBasePath(request) + "/selectRole");
		else
			response.sendRedirect(General.getBasePath(request) + "/main");
	}
	
	private void initSessionData(HttpSession session) {
		UserDetails principal = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		User loginUser = userService.getUserByLoginName(principal.getUsername());
		List<Role> roles = roleService.getRolesByUserId(loginUser.getId());
		session.setAttribute(WebConstants.WEB_SESSION_ALLROLES, roles);
		session.setAttribute(WebConstants.WEB_SESSION_ROLE, roles.get(0));
		session.setAttribute(WebConstants.WEB_SESSION_USER, loginUser);
		session.setAttribute(WebConstants.WEB_SESSION_USER_LAST_LOGIN_DATE, loginUser.getLastLoginDate());
	}

}
