package com.madeu.controller.mobile.mobilesnslogin;

import com.madeu.constants.Constants;
import com.madeu.init.ManagerDraftAction;
import com.madeu.service.mobile.mobilelogin.MobileLoginService;
import com.madeu.util.HttpUtil;
import com.madeu.util.RequestLogUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;

@Slf4j
@Controller
public class MobileSnsLoginController extends ManagerDraftAction {
    @Autowired
	private MobileLoginService mobileLoginService;

//	@Autowired
//	private LogHistoryService logHistoryService;

	/**
	 * 로그인 화면 이동
	 * 페이지 처리 없음
	 * request:
	 * response : msgCode, msgDesc
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/mobilesnslogin/naverLoginIntro.do")
	public String naverLoginIntro(HttpSession session, HttpServletRequest request, HttpServletResponse response) {

		log.debug("WebSnsLoginController naverLoginIntro START");

		try{
//			if(!webCheckLogin(session)){
//			}else{
//				return "/web/home/home";
//			}
		}catch(Exception e){
			e.printStackTrace();
		}
		log.debug("WebSnsLoginController naverLoginIntro END");

		return "/web/login/login";
	}

	/**
	 * 로그인 화면 이동
	 * 페이지 처리 없음
	 * request:
	 * response : msgCode, msgDesc
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/mobilesnslogin/naverLoginCallBackIntro.do")
	public String naverLoginCallBackIntro(HttpSession session,HttpServletRequest request, HttpServletResponse response) {

		log.debug("WebSnsLoginController naverLoginCallBackIntro START");

		try{
//			if(!webCheckLogin(session)){
//			}else{
//				return "/web/home/home";
//			}
		}catch(Exception e){
			e.printStackTrace();
		}
		log.debug("WebSnsLoginController naverLoginCallBackIntro END");

		return "/mobile/login/login_naver";
	}

	/**
	 * 로그인 화면 이동
	 * 페이지 처리 없음
	 * request:
	 * response : msgCode, msgDesc
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/mobilesnslogin/kakaoLoginCallBackIntro.do")
	public String kakaoLoginCallBackIntro(HttpSession session,HttpServletRequest request, HttpServletResponse response) {

		log.debug("WebSnsLoginController kakaoLoginCallBackIntro START");

		try{
//			if(!webCheckLogin(session)){
//			}else{
//				return "/web/home/home";
//			}
		}catch(Exception e){
			e.printStackTrace();
		}
		log.debug("WebSnsLoginController kakaoLoginCallBackIntro END");

		return "/mobile/login/login_kakao";
	}

	/**
	 * 로그인 화면 이동
	 * 페이지 처리 없음
	 * request:
	 * response : msgCode, msgDesc
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/mobilesnslogin/appleLoginCallBackIntro.do")
	public String appleLoginCallBackIntro(HttpSession session, String apple_data, HttpServletRequest request, HttpServletResponse response) {

		log.debug("WebSnsLoginController appleLoginCallBackIntro START");

		try{
//			String[] datas = apple_data.split("[&]");
//			String code = "";
//			String id_token = "";
//			for(String data : datas ) {
//				if(data.equals("code=")) {
//					code = data.replace("code=", "");
//				if(data.equals("id_token=")) {
//					id_token = data.replace("id_token=", "");
//				}
//			}

//			SignedJWT signedJWT = SignedJWT.parse(id_token);
//			JWTClaimsSet payload = signedJWT.getJWTClaimsSet();
//
//			String publicKeys = HttpClientUtils.doGet("https://appleid.apple.com/auth/keys");
//	        ObjectMapper objectMapper = new ObjectMapper();
//	        Keys keys = objectMapper.readValue(publicKeys, Keys.class);
//
//	        boolean signature=false;
//	        for (Key key : keys.getKeys()) {
//	        	 RSAKey rsaKey = (RSAKey) JWK.parse(objectMapper.writeValueAsString(key));
//	             RSAPublicKey publicKey = rsaKey.toRSAPublicKey();
//	             JWSVerifier verifier = new RSASSAVerifier(publicKey);
//	             if (signedJWT.verify(verifier)) {
//	            	 signature=true;
//	            	 logger.warn("복호화 성공");
//	             }
//	        }


		}catch(Exception e){
			e.printStackTrace();
		}
		log.debug("WebSnsLoginController appleLoginCallBackIntro END");

		return "/mobile/login/login_apple";
	}


	/** 애플 sns 로그인 redirect 페이지 */
//	@RequestMapping(value="/websnslogin/appleLoginCallBackIntro.do")
//	@ResponseBody
//	public String appleLoginCallBackIntro(@RequestBody MultiValueMap<String, Object> data, HttpServletRequest request) {
//		//전달 받은 data에서 token 값 저장
//		//String id_token = data.get("id_token").toString();
//		String email = "";
//
//		log.debug("WebSnsLoginController snsApplelogin START");
//
//		try {
//				//token값 decode처리
//			//log.debug("WebSnsLoginController appleLoginCallBackIntro START :" + id_token);
//
//		    SignedJWT signedJWT = SignedJWT.parse(id_token);
//				//token값에서 payload 저장
//		    ReadOnlyJWTClaimsSet payload = signedJWT.getJWTClaimsSet();
//		    payload에서 email 값 저장
//		    email = payload.getClaim("email").toString();
//
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//
//		log.debug("WebSnsLoginController snsApplelogin END");
//
//		return "/web/login/login_apple";
//	}

	/**
	 * <b>로그인</b>
	 * 페이지 처리 없음
	 * request:
	 * response : msgCode, msgDesc
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/mobilesnslogin/snsLogin.do")
	public ModelAndView snsLogin(HttpSession session, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
		log.debug("WebSnsLoginController snsLogin START");

		HashMap<String, Object> paramMap = HttpUtil.getParameterMap(request);
		HashMap<String, Object> map = new HashMap<String, Object>();

		StringBuffer errorMsg = new StringBuffer();

		try{
			HashMap<String, Object> visitLogParamMap = RequestLogUtil.getVisitLogParameterMap(request);
			HashMap<String, Object> loginMap = mobileLoginService.snsLogin(paramMap,visitLogParamMap);

			if((Constants.FAIL).equals(String.valueOf(loginMap.get("msgCode")))){
				map.put("msgCode", loginMap.get("msgCode"));
				map.put("msgDesc", loginMap.get("msgDesc"));
			}else{
				log.debug("======================== USER INFO START ==========================");
				log.debug("ntUserId      : "+loginMap.get("ntUserId"));
				log.debug("loginId       : "+loginMap.get("loginId"));
				log.debug("userName      : "+loginMap.get("userName"));
				log.debug("userType      : "+loginMap.get("userType"));
				log.debug("======================== USER INFO END ============================");

				log.debug("session     : "+session);

				// 회원
				session.setAttribute("ntUserId",loginMap.get("ntUserId"));
				session.setAttribute("loginId",loginMap.get("loginId"));
				session.setAttribute("userName",loginMap.get("userName"));
				session.setAttribute("profileImageUrl",loginMap.get("profileImageUrl"));
				session.setAttribute("interestKeyword",loginMap.get("interestKeyword"));
				session.setAttribute("userType",loginMap.get("userType"));

				map.put("msgCode", loginMap.get("msgCode"));
				map.put("msgDesc", loginMap.get("msgDesc"));
				map.put("type", loginMap.get("type"));
			}

		}catch(Exception e){
			e.printStackTrace();
			errorMsg.append(e);
		}finally {
			if(Constants.OK == map.get("msgCode")) {

			}else{
				map.put("msgCode", Constants.FAIL);
				map.put("success", false);
				if(null == map.get("msgDesc") || ("").equals(map.get("msgDesc"))) {
					map.put("msgDesc","정상적으로 수행되지 않았습니다. (E0122)");
				}
			}

			try {
				HashMap<String, Object> visitLogParamMap = RequestLogUtil.getVisitLogParameterMap(request);
				HashMap<String, Object> insertMap = new HashMap<String, Object>();

				insertMap.put("url", "/websnslogin/snsLogin.do");
				insertMap.put("func", "snsLogin");
				insertMap.put("funcName", "SNS로그인");
				insertMap.put("service", "mobileLoginService");
				insertMap.put("serviceName", "SNS로그인");
				insertMap.put("requestValue", String.valueOf(paramMap));
				insertMap.put("responseValue", String.valueOf(map));
				insertMap.put("tId", map.get("tId"));
				if((String.valueOf(errorMsg)).equals("") || (String.valueOf(errorMsg) == null) || String.valueOf(errorMsg).length() == 0){
					insertMap.put("resultCode", "SUCCESS");
				}else{
					insertMap.put("resultCode", "ERROR");
				}
				insertMap.put("resultMsg", String.valueOf(errorMsg));
				insertMap.put("ntUserId", paramMap.get("ntUserId"));

//				logHistoryService.insertLogHistory(insertMap, visitLogParamMap);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		log.debug("WebSnsLoginController snsLogin END");
		return HttpUtil.makeHashToJsonModelAndView(map);
	}
}
