package com.style24.front.support.interceptor;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.mobile.device.Device;
import org.springframework.mobile.device.DeviceUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.gagaframework.web.util.GagaStringUtil;
import com.style24.front.support.security.session.TsfSession;

import lombok.extern.slf4j.Slf4j;

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

	private static final String APP_PREFIX = "istyle24@";

	@Autowired
	private Environment env;

	@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());

		// Set APP Info.
		this.setAppInfo(request);

		// Set 프론트구분
		this.setFrontGb(request);

		// 앱 검사를 위해
		// 1.웹으로 접근하고
		// 2.특정IP(아이스타일본사: 180.71.39.150, 한세엠케이: 106.251.248.202, 한세드림: 218.144.146.18)가 아니면
		// String ipAddr = TsfSession.getIpAddress();
		// String active = env.getProperty("spring.profiles.active");
		// List<String> ipWhiteList = new ArrayList<>();
		// ipWhiteList.add("180.71.39.150");			// 아이스타일 본사
		// ipWhiteList.add("106.251.248.202");			// 한세엠케이
		// ipWhiteList.add("218.144.146.18");			// 한세드림
		// ipWhiteList.add("14.129.18.111");			// 스윗트래커
		// ipWhiteList.add("58.180.40.40");			// 코마스
		// ipWhiteList.add("221.150.126.74");			// 모비온
		// ipWhiteList.add("221.150.126.75");			// 모비온
		//
		// log.info("IP Address: [{}]", ipAddr);
		// if (TsfSession.getAttribute("isApp").equals("false") &&
		// 	!ipWhiteList.contains(ipAddr) &&
		// 	!"locd".equals(active) &&
		// 	!"tsit".equals(active)) {
		// 	response.sendRedirect("https://m.istyle24.com");
		// 	return false;
		// }

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

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

	/**
	 * UserAgent 값을 이용한 APP 설정
	 * 		APP에서 접속 시 다음과 같이 UserAgent 값이 들어옴.
	 * 		예) Agent : 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,istyle24@style24_1.0.0
	 * @param request
	 */
	private void setAppInfo(HttpServletRequest request) {
		// User Agent
		String userAgent = request.getHeader("User-Agent").toLowerCase();
		// log.info("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) {
//						TsfSession.setAttribute("deviceToken", oneData);
					}
					cnt++;
				}
			}
		} else {
			TsfSession.setAttribute("isApp", "false");
		}
	}

	/**
	 * 프론트구분 가져오기
	 * @return P:PC, M:모바일, A:앱
	 */
	private void setFrontGb(HttpServletRequest request) {
		Device device = DeviceUtils.getCurrentDevice(request);

		if (device == null || device.isNormal()) {
			TsfSession.setAttribute("frontGb", "P");
		} else {
			log.info("TsfSession.isApp: {}", TsfSession.getAttribute("isApp"));
			log.info("device.isMobile: {}", device.isMobile());
			log.info("device.isNormal: {}", device.isNormal());
			log.info("device.isTablet: {}", device.isTablet());

			if ("true".equals(TsfSession.getAttribute("isApp"))) {
				TsfSession.setAttribute("frontGb", "A");
			} else {
				TsfSession.setAttribute("frontGb", "M");
			}
		}
	}

}
