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

import java.io.IOException;
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.faics.cmmn.service.impl.CodeMapper;
import kcg.faics.cmmn.service.impl.LogMapper;
import kcg.faics.member.service.MemberService;
import kcg.faics.member.vo.MemberVO;
import kcg.faics.sec.service.impl.SecurityMapper;

import org.apache.commons.lang3.StringUtils;
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;

/** 
 * LoginSuccessHandler.java
 * @author 임새미 
 * @since 2016. 10. 11.
 *
 *  	 수정일                     수정자                                       수정내용
 *  -------------	--------	---------------------------
 *  2016. 10. 11. 	    임새미				       최초생성
 * 
 */
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
	
	/**
	 * 사용자 서비스 객체.
	 */
	@Resource(name = "memberService")
	private MemberService memberService;
	
	@Resource(name = "securityMapper")
	SecurityMapper securityMapper;
	
	@Resource(name = "codeMapper")
	CodeMapper codeMapper;
	
	@Resource(name = "logMapper")
	LogMapper logMapper;
	
	@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();
			
			Map<String, Object> rptApprove = securityMapper.getReportAgentApprove(userId);
			
			String head = null;
			String section = null;
			if (rptApprove != null) {
				head = (String) rptApprove.get("head");
				section = (String) rptApprove.get("section");
			}
			/* 계장? */
			user.setAuthHead(head != null && head.equals(userId) ? 1 : 0);
			
			/* 차장? */
			user.setAuthSection(section != null && section.equals(userId) ? 1 : 0);
			
			
			Map<String, Object> rptAu = (Map<String, Object>) securityMapper.getReportAgentAuCode(userId);
			int authCode = 0;
			if (rptAu != null) {
				
				if (rptAu.get("code") == null) {
					authCode = 32;
				} else {
					authCode = Integer.parseInt(rptAu.get("code").toString());
				}
			}
			user.setAuthCode(authCode);
			user.setAuthSearch(authCode & 1);
			user.setAuthStatistics(authCode & 2);
			user.setAuthWaitList(authCode & 4);
			user.setAuthManage(authCode & 8);
			user.setAuthProxySection(authCode & 16);
			user.setAuthProxyHead(authCode & 32);
			
			/* auth_approve? */
			user.setAuthApprove(user.getAuthHead() | user.getAuthSection() | user.getAuthProxyHead() | user.getAuthProxySection());
			
			String duties = user.getDuties();
			// if ($this->auth_proxy_section || $this->auth_section) ??
			if (user.getAuthProxySection() > 0 || user.getAuthSection() > 0) {
				duties = "03";
			}
			// if ($this->auth_proxy_head || $this->auth_head) ??
			if (user.getAuthProxyHead() > 0 || user.getAuthHead() > 0) {
				duties = "04";
			}
			user.setDuties(duties);
			
			/* auth_type */
			user.setAuthType(getAuthType(user.getPlace1()));
			/* Place 1 */
			user.setPlace1Str(codeMapper.getPlace1NameByCode(user.getPlace1(), false));
			user.setPlace1Yak(codeMapper.getPlace1NameByCode(user.getPlace1(), true));
			/* Place 2 */
			user.setPlace2Str(codeMapper.getPlace2NameByCode(user.getPlace1(), user.getPlace2()));
			/* Position */
			user.setPositionStr(codeMapper.getPositionNameByCode(user.getPosition()));
			/* Duties */
			user.setDutiesStr(codeMapper.getDutiesNameByCode(user.getDuties()));
			
			/* IP정보 */
			String ip = request.getHeader("X-FORWARDED-FOR");
			if (StringUtils.isBlank(ip)) {
				ip = request.getRemoteAddr();
			}
			user.setIp(ip);
			
			/* 로그인 플래그 */
			user.setLoginchk("Y");
			
			/* 로그인 로그 등록 */
			securityMapper.updateLoginInfo(user);
			logMapper.insertLoginoutLog(user, 1);
			
			/* 관리자? */
			int roleLev = user.getRolelevel();
			user.setAuthAdmin((roleLev <= propertiesService.getInt("adminLevel")) ? 1 : 0);
			user.setIsAdmin(roleLev <= propertiesService.getInt("adminLevel"));
			user.setIsSysAdmin((roleLev <= propertiesService.getInt("sysAdminLevel")) || propertiesService.getString("sysAdminId").equals(userId));
			
			/* 로그인 실패횟수 초기화 */
			MemberVO memberVO = new MemberVO();
			memberVO.setUserid(user.getUserid());
			if (user.getType() == 1) {
				memberVO.setUsertype("f");
			}
			memberService.initChkcnt(memberVO);
			
			/* 설정된 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;
	}
	
}
