package com.style24.front.support.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.style24.front.support.security.session.TsfSession;

import lombok.extern.slf4j.Slf4j;

import com.gagaframework.web.util.GagaStringUtil;

/**
 * 모든 Request에 대한 선처리
 * 
 * @author gagamel
 * @since 2020. 9. 11
 */
@Component
@Slf4j
public class TsfDefaultInterceptor extends HandlerInterceptorAdapter {

	private static final String APP_PREFIX = "style24@";

//	@Value("${has-ssl}")
//	private String hasSsl;

//	@Autowired
//	private WfoPolicyService policyService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		log.info("request.isSecure(): [{}]", request.isSecure());
		log.info("request.getServerName(): [{}]", request.getServerName());
		log.info("request.getRequestURI(): [{}]", request.getRequestURI());
		log.info("request.getRequestURL(): [{}]", request.getRequestURL());
		log.info("request.getQueryString(): [{}]", request.getQueryString());

//		// 설정된 HTTPS 페이지 확인
//		String requestUrl = request.getRequestURL().toString();
//		boolean bHttpsPage = this.isHttpsPage(isSslServer, requestUrl, request.getRequestURI());
//		log.debug("bHttpsPage: [{}]", bHttpsPage);
//		if (bHttpsPage) {
//			requestUrl = requestUrl.replace("http://", "https://");
//			log.debug("requestUrl: [{}]", requestUrl);
//			response.sendRedirect(requestUrl);
//			return false;
//		}
//
//		// Set Meta Info.
//		policyService.setMetaInfo(FoConstants.SITE_CD);
//
//		String queryString = GagaStringUtil.convertParameterToQueryString(request.getParameterMap());
//		if (StringUtils.isNotBlank(queryString))
//			queryString = "?" + queryString;
//		log.debug("queryString: [{}]", queryString);
//
//		// Set APP Info.
//		this.setAppInfo(request);

		return super.preHandle(request, response, handler);
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
		ModelAndView modelAndView) throws Exception {
		// Do nothing
	}

	/**
	 * HTTPS로 적용할 페이지인지 체크
	 * @param requestUrl - Request URL
	 * @param requestUri - Request URI
	 * @return true/false
	 * @author gagamel
	 * @since 2020. 2. 3
	 */
	private boolean isHttpsPage(boolean isSslServer, String requestUrl, String requestUri) {
		// https 이어야 하는 화면의 URL 목록
		final String[] httpsUrls = {"/customer", "/mypage", "/order"};

		// 1.설정된 HTTPS URL 값이 없거나
		// 2.SSL이 적용되지 않은 서버이거나
		// 3.https로 시작되었거나
		// 4.Ajax 호출인 경우
		if (!isSslServer || requestUrl.startsWith("https://"))
			return false;

		for (String httpsUrl : httpsUrls) {
			log.debug("requestUri: {}, httpsUrl: {}", requestUri, httpsUrl);
			if (requestUri.startsWith(httpsUrl)) {
				return true;
			}
		}

		return false;
	}

	/**
	 * UserAgent 값을 이용한 APP 설정
	 * 		APP에서 접속 시 다음과 같이 UserAgent 값이 들어옴.
	 * 		예) Mozilla/5.0 (Linux; Android 10; Android SDK built for x86 Build/QSR1.190920.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/74.0.3729.185 Mobile Safari/537.36,wivismall@WIVIS_1.0.5
	 * @param request
	 */
	private void setAppInfo(HttpServletRequest request) {
		// User Agent
		String userAgent = request.getHeader("User-Agent").toLowerCase();
		log.debug("userAgent: [{}]", userAgent);

		if (userAgent.indexOf("iphone") > -1 ||
			userAgent.indexOf("ipod") > -1 ||
			userAgent.indexOf("ipad") > -1) {
			TsfSession.setAttribute("osType", "I");
		} else if (userAgent.indexOf("android") > -1) {
			TsfSession.setAttribute("osType", "A");
		}

		int offset = userAgent.lastIndexOf(APP_PREFIX);

		if (offset > 0) {
			TsfSession.setAttribute("isApp", "true");

			String strAppInfo = GagaStringUtil.replace(userAgent.substring(offset), APP_PREFIX, "");
			String[] arrApp = strAppInfo.split("_");
			if (arrApp != null) {
				int cnt = 0;
				for (String oneData : arrApp) {
					if (cnt == 0) {
						TsfSession.setAttribute("appName", oneData);
					} else if (cnt == 1) {
						TsfSession.setAttribute("appVersion", oneData);
//					} else if (cnt == 2) {
//						WfoSession.setAttribute("deviceToken", oneData);
					}
					cnt++;
				}
			}
		} else {
			TsfSession.setAttribute("isApp", "false");
		}
	}

}
