package com.rg.util.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import com.rg.login.dto.CustomUserDetails;
import com.rg.login.dto.UserDetailsVO;
import com.rg.login.service.LoginService;
import com.rg.util.GeoLite2;
import com.rg.util.IP;
import com.rg.util.LocaleUtil;
import com.rg.util.RedisService3;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

@Controller
@CrossOrigin(origins = "http://localhost", maxAge = 3600)
public class EnvironmentController {

	private final Logger logger = LogManager.getLogger(EnvironmentController.class);

	@Autowired
	private LoginService loginService;

	@Autowired
	private RedisService3 redisService;
	
	@RequestMapping(value = {"/getEnvironment.do", "/{lang}/getEnvironment.do"})
	@ResponseBody
	public Map<String, String> getEnvironment(@PathVariable("lang") Optional<String> langVal,
			HttpServletRequest request, HttpServletResponse response) {
		
		LocaleUtil localeUtil = new LocaleUtil();
		
		if ("ko".equals(langVal.toString()) || "en".equals(langVal.toString())) {
			
			localeUtil.setLocale(langVal.toString(), request, response);
			
		} else {
			
			Cookie cookieLocale = WebUtils.getCookie(request, 
					"org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE");
			
			String cookieLocaleValue = "";
			
			if (cookieLocale != null) {
				cookieLocaleValue = cookieLocale.getValue();
			}
			
			if (!"ko".equals(cookieLocaleValue) && !"en".equals(cookieLocaleValue)) {
				localeUtil.setLocale(null, request, response);
			}
		}
		
		
		HttpSession session = request.getSession();

		UserDetailsVO vo = null;
		
		CustomUserDetails userInfo = null;
		
		String loginId = null;
		String loginUserName = null;
		
		try {
			if (SecurityContextHolder.getContext().getAuthentication() != null &&
				SecurityContextHolder.getContext().getAuthentication().isAuthenticated()) {
				if (SecurityContextHolder.getContext().getAuthentication().getDetails() instanceof CustomUserDetails) {
					userInfo = (CustomUserDetails)SecurityContextHolder.getContext().getAuthentication().getDetails();
					loginId = userInfo.getUsername();
					loginUserName = loginService.getUserName(loginId);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		logger.debug("#### loginUserName : " + loginUserName);
		
		String redisKey = "LOGIN||SESSION||" + loginId + "||" + session.getId();
		
		vo = redisService.selectRedisSession(redisKey);
		
		loginId = vo == null ? "" : vo.getLoginId();
		
		Map<String, String> map = new HashMap<String, String>();
		
		if (vo != null && vo.getLoginId() != null && !"".equals(vo.getLoginId()) && !"null".equals(vo.getLoginId())) {
			map.put("loginId", vo.getLoginId());
			map.put("loginUserName", vo.getLoginUserName());
			
			int sessionTime = 60 * 60 * 10;
			redisService.setTimeOutSecond(redisKey, sessionTime);
		}


		String lang = "";
		Cookie[] cs = request.getCookies();
		if (cs != null) {
			for (int i=0; i < cs.length; i++) {
				Cookie c = cs[i];
				if ("org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE".equals(c.getName())) {
					lang = c.getValue();
				}
			}
		}
		
		
		String currentLocale = localeUtil.getLocale().getLanguage();
		
		if (lang != null && !"".equals(lang)) {
			currentLocale = lang;
			
		} else {
			String country = GeoLite2.getCountry(request, IP.getClientIP(request));

			if ("KR".equals(country)) {
				currentLocale = "ko";
			} else {
				currentLocale = "en";
			}
		}
		
		localeUtil.setLocale(currentLocale, request, response);

		
		if (lang != null && !"".equals(lang)) {
			map.put("locale", lang);
		} else {
			map.put("locale", currentLocale);
		}
		
		
		CsrfToken token = (CsrfToken) request.getAttribute("_csrf");
		
		logger.debug("#### csrfToken : " + token.getToken());
		
		return map;
	}


	@RequestMapping(value = {"/getEmptyRequest.do", "/getEmptyRequest1.do", "/getEmptyRequest2.do", "/getEmptyRequest3.do", "/getEmptyRequest4.do"})
	@ResponseBody
	public Map<String, String> getEmptyRequest(HttpServletRequest request, HttpServletResponse response) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("RequestURI", request.getRequestURI());
		return map;
	}
}
