package com.uas.platform.b2b.support;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Set;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.uas.platform.b2b.model.Role;
import com.uas.platform.b2b.model.User;
import com.uas.platform.b2b.service.UserService;
import com.uas.platform.core.model.Constant;

public class CustomAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

	@Autowired
	private UserService userService;

	private RequestCache requestCache = new HttpSessionRequestCache();

	@Override
	public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response,
			final Authentication authentication) throws ServletException, IOException {
		logSession(request, authentication);

		final SavedRequest savedRequest = requestCache.getRequest(request, response);

		if (savedRequest == null) {
			clearAuthenticationAttributes(request);
			return;
		}
		final String targetUrlParameter = getTargetUrlParameter();
		if (isAlwaysUseDefaultTargetUrl() || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
			requestCache.removeRequest(request, response);
			clearAuthenticationAttributes(request);
			return;
		}

		clearAuthenticationAttributes(request);
		PrintWriter printWriter = response.getWriter();
		printWriter.append(savedRequest.getRedirectUrl());
		printWriter.flush();
		printWriter.close();
	}

	public void setRequestCache(final RequestCache requestCache) {
		this.requestCache = requestCache;
	}

	/**
	 * 登录认证成功后，user写到session
	 * 
	 * @param request
	 * @param authentication
	 */
	private void logSession(HttpServletRequest request, Authentication authentication) {
		User user = userService.findUserByUserUU(Long.parseLong(authentication.getName()));
		user.setCurrentEnterprise();
		Set<Role> roles = user.getRoles();
		if (!CollectionUtils.isEmpty(roles)) {
			for (Role role : roles) {
				if (role.isSys()) {// 超级账号
					user.setIssys(Constant.YES);
					break;
				}
			}
		}
		request.getSession().setAttribute("user", user);
	}

}
