/** 
 * LoginSuccessHandler.java
 * @author 임새미 
 * @since 2016. 10. 11.
 *
 *  	 수정일                     수정자                                       수정내용
 *  -------------	--------	---------------------------
 *  2016. 10. 11. 	    임새미				       최초생성
 * 
 */
package kcg.imis.sec;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

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

import kcg.imis.cmmn.aop.CommonAop;
import kcg.imis.cmmn.mapper.CodeMapper;
import kcg.imis.cmmn.service.LogService;
import kcg.imis.sec.mapper.SecurityMapper;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import egovframework.rte.fdl.property.EgovPropertyService;

/**
  * @FileName : LoginSuccessHandler.java
  * @Project : 국제해양프로젝트
  * @Date : 2018. 3. 29. 
  * @작성자 : Moon
  * @변경이력 : 
  * @프로그램 설명 :
 */
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(LoginSuccessHandler.class);
	
	/**
	 * 사용자 서비스 객체.
	 */
	/*@Resource(name = "memberService")
	private MemberService memberService;*/
	
	@Resource(name = "securityMapper")
	SecurityMapper securityMapper;
	
	@Resource(name = "codeMapper")
	CodeMapper codeMapper;
	
	@Resource(name = "logService")
	LogService logService;
	
	@Resource(name = "propertiesService")
	private EgovPropertyService propertiesService;
	
	
	private RedirectStrategy redirectStrategy =  new DefaultRedirectStrategy();
	
	private String successUrl = "/";
	
	public void setSuccessUrl(String successUrl){
		this.successUrl = successUrl;
	}
	
	
	/**
	 * security 인증 성공 이후의 절차를 진행한다.
	 * 
	 * @param request request객체
	 * @param response response객체
	 * @param authentication authentication객체
	 * @exception IOException, ServletException 입출력, 서블릿 예외
	 */
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		
		try {
			LoginUserVO user = UserUtil.getMemberInfo();
			
			HttpSession session = request.getSession();
			session.setAttribute("userVO", user);
				
			String userId = user.getUserid();
			
			user.setAuthHead(user.getUsegrade() == 3 ? 1 : 0);
			user.setAuthSection(user.getUsegrade() == 4 ? 1 : 0);
			
			
			user.setAuthAdmin(("admin".equals(user.getUserid()) || user.getAuthManage() > 0 && "PS00".equals(user.getPlace1())) ? 1 : 0 );
			
			user.setAuthApprove(user.getAuthHead() | user.getAuthSection() | user.getAuthProxyHead() | user.getAuthProxySection());
			
			String duties = user.getDuties();
			if (user.getAuthProxySection() > 0 || user.getAuthSection() > 0) {
				duties = "03";
			}
			if (user.getAuthProxyHead() > 0 || user.getAuthHead() > 0) {
				duties = "04";
			}
			user.setDuties(duties);
			
			 /*auth_type */
			user.setAuthType(getAuthType(user.getPlace1()));
			
			 /*IP정보*/ 
			String ip = request.getHeader("X-FORWARDED-FOR");
			if (StringUtils.isBlank(ip)) {
				ip = request.getRemoteAddr();
			}
			
			
			/* 관리자? */
			int roleLev = user.getRolelevel();
			
			user.setIsAdmin((roleLev <= propertiesService.getInt("adminLevel")) ? true : false);
			user.setIsSysAdmin((roleLev <= propertiesService.getInt("sysAdminLevel")) || propertiesService.getString("sysAdminId").equals(userId) ? true : false);
			
			
			try{
				
				String os = request.getParameter("os");
				String bw = request.getParameter("browser");
				String bwVersion = request.getParameter("browser-version");
				
				HashMap<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("os", os);
				paramMap.put("bw", bw);
				paramMap.put("bwVersion", bwVersion);
				paramMap.put("userid", user.getUserid());
				paramMap.put("name", user.getName());
				paramMap.put("userip", request.getRemoteAddr());
				paramMap.put("place1", user.getPlace1());
				paramMap.put("place2", user.getPlace2());
				paramMap.put("position", user.getDuties());
				
				logService.insertLoginLog(paramMap);
			}catch(Exception e){
				LOGGER.error("fail login log...............");
				LOGGER.error(e.getMessage());
			}
			
			/* 설정된 successUrl로 리다이렉트한다.*/
			redirectStrategy.sendRedirect(request, response, successUrl);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	
	/**
	 * 소속기관에 따른 기관 타입을 결정한다.
	 * 
	 * @param place 소속기관 코드
	 * @return 기관 타입
	 */
	private int getAuthType(String place){
		int type = 10;
		if ("PS00".equalsIgnoreCase(place)) {
			type = 1;			
		} else if ("PS92".equalsIgnoreCase(place) || "PS93".equalsIgnoreCase(place) || "PS94".equalsIgnoreCase(place) || "PS91".equalsIgnoreCase(place) || "ps90".equalsIgnoreCase(place)) {
			type = 6;						
		}
		return type;
	}
	
}
