package egovframework.com.cmm.selfauth;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.sci.v2.ipinv2.secu.SciSecuManager;

import egovframework.com.cmm.UserVO;
import egovframework.let.cop.bbs.service.BoardVO;


/**
 * 휴대폰 인증 처리를 위한 컨트롤러 클래스
 * @author 공통 서비스 개발팀 이삼섭
 * @since 2009.03.19
 * @version 1.0
 * @see
 *
 * <pre>
 * << 개정이력(Modification Information) >>
 *
 *   수정일      수정자          수정내용
 *  -------    --------    ---------------------------
 *  2009.03.19  이삼섭          최초 생성
 *  2009.06.29  한성곤	       2단계 기능 추가 (댓글관리, 만족도조사)
 *  2011.08.31  JJY            경량환경 템플릿 커스터마이징버전 생성
 *
 *  </pre>
 */
@Controller
public class IpinauthController {

	@Value("#{globalSettings['Globals.Site.URL']}")
	private String SITE_URL;
	
	@Value("#{globalSettings['Globals.ipinauth.siteId']}")
	private String IPINAUTH_SITE_ID;
	@Value("#{globalSettings['Globals.ipinauth.srvNo']}")
	private String IPINAUTH_SRV_NO;

	private static final Logger LOGGER = LoggerFactory.getLogger(IpinauthController.class);
	
	/**
	 * (사용자)아이핀서비스 요청 Sample Page - input 1
	 */
	@RequestMapping("/web/cop/bbs/ipinInputSeedV2.do")
	public String ipinInputSeedV2(HttpServletRequest request, ModelMap model, RedirectAttributes redirectAttributes)throws Exception {
		return "web/cop/selfauth/ipin_input_seed";
	}
	
	/**
	 * (사용자)아이핀서비스 요청 Sample Page - request 2
	 */
	@RequestMapping("/web/cop/bbs/ipinRequestSeedV2.do")
	public String ipinRequestSeedV2(HttpServletRequest request, ModelMap model, RedirectAttributes redirectAttributes)throws Exception {
		return "web/cop/selfauth/ipin_request_seed";
	}
	
	/**
	 * (사용자)아이핀서비스 요청 Sample Page - popup 3
	 */
	@RequestMapping("/web/cop/bbs/ipinPopupSeedV2.do")
	public String ipinPopupSeedV2(HttpServletRequest request, ModelMap model, RedirectAttributes redirectAttributes)throws Exception {
		return "web/cop/selfauth/ipin_popup_seed";
	}
	
	/**
	 * (사용자)아이핀서비스 요청 Sample Page - result 4
	 */
	@RequestMapping("/web/cop/bbs/ipinResultSeedV2.do")
	public String ipinResultSeedV2(HttpServletRequest request, ModelMap model, RedirectAttributes redirectAttributes)throws Exception {
		return "web/cop/selfauth/ipin_result_seed";
	}
	
	/**
	 * (사용자)아이핀인증 안내 화면
	 *
	 * @param 
	 * @return
	 * @throws Exception
	 */
//	@RequestMapping("/web/cop/selfauth/authentication.do")
//	public String authentication(ModelMap model) throws Exception {
//		
//		model.addAttribute("SITE_URL", SITE_URL);
//		return "web/cop/selfauth/authentication";
//	}
	
	/**
	 * (사용자) 아이핀 본인인증 요청 1 pop
	 *
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/web/cop/selfauth/ipinauth.do")
	public String ipinauth(HttpServletRequest request, ModelMap model, RedirectAttributes redirectAttributes)throws Exception {
		// 사이렌 요청 URL 등록 :  /web/cop/selfauth/ipinauth.do 
		// test 서버 서비스 번호 001003
		
		java.util.Random ran = new Random();
		//랜던 문자 길이
		int numLength = 16;
		String randomStr = "";

		for (int i = 0; i < numLength; i++) {
			//0 ~ 9 랜덤 숫자 생성
			randomStr += ran.nextInt(10);
		}

		String reqNum = randomStr;
		
		String exVar = "0000000000000000"; // 복호화용 임시필드
		
		request.getSession().setAttribute("reqNum", reqNum); // 결과값 복호화시 필요
		
	    //01. 암호화 모듈 선언
		SciSecuManager seed  = new SciSecuManager();
		
		// 아이핀 모듈 암호화 키
		seed.setInfoPublic(IPINAUTH_SITE_ID,"BA92414622515048479AB7B12A6DBD3A"); 
		
		String encStr = "";
		String reqInfo       = reqNum+"/"+IPINAUTH_SITE_ID+"/"+IPINAUTH_SRV_NO+"/"+exVar;  // 데이터 암호화
		
		// 1차 암호화
		encStr               = seed.getEncPublic(reqInfo);
		// 위변조 검증 값 등록
		String hmacMsg  = seed.getEncReq(encStr,"HMAC");

		// 2차 암호화
		reqInfo  = seed.getEncPublic(encStr + "/" + hmacMsg + "/" + "00000000");  //2차암호화
		
		//암호화키 값을 위한 아이디
		reqInfo = seed.EncPublic(reqInfo + "/" + IPINAUTH_SITE_ID + "/"  + "00000000");
		
//		request.getSession().setAttribute("encReqNum", seed.getEncPublic(seed.getEncReq(reqNum,"HMAC"))); // ?
		
		request.getSession().setAttribute("reqInfo", reqInfo); // 본인확인 요청 정보
		request.getSession().setAttribute("SITE_URL", SITE_URL); // 사이트 URL
		request.getSession().setAttribute("reqNum", reqNum); // 요청번호 복호화 시 사용

		return "web/cop/selfauth/ipinauth";
	}
	
	/**
	 * (사용자)아이핀인증 결과 리턴 2 
	 *
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/web/cop/selfauth/ipinResultSeed.do")
	public String ipinResultSeed(HttpServletRequest request, ModelMap model, RedirectAttributes redirectAttributes)throws Exception {
		
		String retInfo   = request.getParameter("retInfo").trim();
		String tranjectionReqNum = (String)request.getSession().getAttribute("reqNum");
		
		//복화화용 변수
		String encPara      = "";
		String decPara      = "";
	    String encMsg       = "";                                                        // HMAC 메세지

	    String discrHash    = "";                                                        // 중복가입확인정보
	    String name         = "";                                                        // 성명
//	    String reqNum       = "";                                                        // 요청번호(복호화)
//	    String vDiscrNo     = "";                                                        // 가상식별번호
//	    String result       = "";                                                        // 결과값 (1인경우에만 정상)
//		String age          = "";
//	    String sex          = "";
//		String ip           = "";
//	    String authInfo     = "";														 // 발급수단정보	
//	    String birth        = "";
//	    String fgn          = "";                                                        // 외국인구분
//		String ciVersion	= "";														 // 연계정보 버젼
//		String ciscrHash    = "";                                                        // 연계정보

		String msgChk       = "N";                                                    // 위조/변조 검증 결과
		
		// 1. 암호화 모듈 (jar) Loading
		SciSecuManager sciSecuMg  = new SciSecuManager();
		sciSecuMg.setInfoPublic("YYY001","BA92414622515048479AB7B12A6DBD3A");
		
		retInfo  = sciSecuMg.getDec(retInfo, tranjectionReqNum);
		
		// 2.1차 파싱---------------------------------------------------------------
		int inf1 = retInfo.indexOf("/",0);
		int inf2 = retInfo.indexOf("/",inf1+1);

		encPara  = retInfo.substring(0,inf1);         //암호화된 통합 파라미터
		encMsg   = retInfo.substring(inf1+1,inf2);    //암호화된 통합 파라미터의 Hash값

        if(sciSecuMg.getMsg(encPara).equals(encMsg)){
            msgChk="Y";
        }
		
        // 비정상 접근 처리
		if(msgChk.equals("N")) {
			model.addAttribute("msgChk", msgChk);
			return "web/cop/selfauth/ipinResultSeed";
		}
		
        // 4.파라미터별 값 가져오기 ---------------------------------------------------------------
        decPara  = sciSecuMg.getDec(encPara, tranjectionReqNum);

		int info1 = decPara.indexOf("/",0);
        int info2 = decPara.indexOf("/",info1+1);
        int info3 = decPara.indexOf("/",info2+1);
        int info4 = decPara.indexOf("/",info3+1);
    	int info5 = decPara.indexOf("/",info4+1);
        int info6 = decPara.indexOf("/",info5+1);
        int info7 = decPara.indexOf("/",info6+1);
        int info8 = decPara.indexOf("/",info7+1);
        int info9 = decPara.indexOf("/",info8+1);
        int info10 = decPara.indexOf("/",info9+1);
        int info11 = decPara.indexOf("/",info10+1);
        int info12 = decPara.indexOf("/",info11+1);
        int info13 = decPara.indexOf("/",info12+1);

        name       = decPara.substring(info2+1,info3);
        discrHash  = decPara.substring(info10+1,info11);
        
//		reqNum     = decPara.substring(0,info1);
//        vDiscrNo   = decPara.substring(info1+1,info2);
//        result     = decPara.substring(info3+1,info4);
//        age        = decPara.substring(info4+1,info5);
//        sex        = decPara.substring(info5+1,info6);
//        ip         = decPara.substring(info6+1,info7);
//        authInfo   = decPara.substring(info7+1,info8);
//        birth      = decPara.substring(info8+1,info9);
//        fgn        = decPara.substring(info9+1,info10);
        
   //   ciVersion  = decPara.substring(info11+1,info12);		//CI관련 데이터는 계약시 설정하는 값입니다.  
   //	ciscrHash  = decPara.substring(info12+1,info13);		//데이터를 원하실 경우 영업팀을 통해 승인받으신후 주석제거 해주십시요
		
		discrHash  = sciSecuMg.getDec(discrHash, tranjectionReqNum); //중복가입확인정보는 한번더 복호화
  //	ciscrHash  = sciSecuMg.getDec(ciscrHash, tranjectionReqNum); //연계정보는 한번더 복호화
		
		// 사용자 세션생성
		UserVO userVO = new UserVO();
		userVO.setName(name);
		userVO.setMblDn(discrHash);
		request.getSession().setAttribute("userVO", userVO);
		
		String returnType = (String)request.getSession().getAttribute("returnType");
		String returnUrl = (String)request.getSession().getAttribute("returnUrl");
		
//		if (!("resveAdd").equals(returnType) && !("resveInqire").equals(returnType)) {
//			BoardVO searchVO = (BoardVO)request.getSession().getAttribute("searchVO");
//			model.addAttribute("searchVO", searchVO);
//		} 
		
		model.addAttribute("returnType", returnType);
		model.addAttribute("returnUrl", returnUrl);
		model.addAttribute("name", name);
		return "web/cop/selfauth/resultSeed";
	}
	
}
