package com.style24.front.support.interceptor;

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.style24.front.biz.service.TsfCommonService;
import com.style24.front.support.env.TsfConstants;
import com.style24.front.support.security.session.TsfSession;
import com.style24.persistence.domain.InflowHst;

import lombok.extern.slf4j.Slf4j;

import com.gagaframework.web.parameter.GagaMap;
import com.gagaframework.web.parameter.GagaParameterUtil;
import com.gagaframework.web.util.GagaCookieUtil;
import com.gagaframework.web.util.GagaStringUtil;

/**
 * 제휴링크 Interceptor
 * 
 * @author gagamel
 * @since 2020. 9. 11
 */
@Component
@Slf4j
public class TsfAflinkInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private TsfCommonService commonService;

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

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// Parameter
		GagaMap params = GagaParameterUtil.getParameterMap(request);

		// 제휴링크코드
		String afLinkCd = params.getString("afLinkCd");
		log.info("afLinkCd: {}", afLinkCd);
		log.info("1.session's afLinkCd: {}", TsfSession.getAttribute("afLinkCd"));
		log.info("1.cookie's afLinkCd: {}", GagaCookieUtil.getCookie(request, TsfConstants.CK_PREFIX + "_afLinkCd"));

		// 제휴링크코드 파라미터 값이 있으면
		if (StringUtils.isNotBlank(afLinkCd)) {
			// 1.유효한 웹제휴채널코드 여부 조회
			String isAvailAfLinkCdYn = commonService.getAvailableAfLinkYn(afLinkCd);
			log.info("isAvailAfLinkCdYn: {}", isAvailAfLinkCdYn);

			// 2.유효한 웹제휴채널코드이고 세션 값과 다르거나 쿠키 값과 다르면 다시 설정
			if (isAvailAfLinkCdYn.equals("Y")) {
//				if (!afLinkCd.equals(TsfSession.getAttribute("afLinkCd"))) {
//					TsfSession.setAttribute("afLinkCd", afLinkCd);
//				} else if (!afLinkCd.equals(GagaCookieUtil.getCookie(request, TsfConstants.CK_PREFIX + "_afLinkCd"))) {
//					TsfSession.setAttribute("afLinkCd", afLinkCd);
//				}
			} else { // 유효한 웹제휴채널코드가 아니면 공백으로
				if (StringUtils.isNotBlank(TsfSession.getAttribute("afLinkCd"))) { // 세션 값이 있으면
					afLinkCd = TsfSession.getAttribute("afLinkCd");
				} else if (StringUtils.isNotBlank(GagaCookieUtil.getCookie(request, TsfConstants.CK_PREFIX + "_afLinkCd"))) { // 쿠키 값이 있으면
					afLinkCd = GagaCookieUtil.getCookie(request, TsfConstants.CK_PREFIX + "_afLinkCd");
				} else { // 세션이나 쿠키 값이 없으면
					afLinkCd = "";
				}
			}
		} else { // 제휴링크 파라미터 값이 없으면
			// 세션과 쿠키에 담긴 값이 없으면 앱과 웹에 따라 OS에 따라 설정
			if (StringUtils.isNotBlank(TsfSession.getAttribute("afLinkCd"))) {
				afLinkCd = TsfSession.getAttribute("afLinkCd");
			} else if (StringUtils.isNotBlank(GagaCookieUtil.getCookie(request, TsfConstants.CK_PREFIX + "_afLinkCd"))) {
				afLinkCd = GagaCookieUtil.getCookie(request, TsfConstants.CK_PREFIX + "_afLinkCd");
			}
			if (StringUtils.isBlank(TsfSession.getAttribute("afLinkCd")) && StringUtils.isBlank(GagaCookieUtil.getCookie(request, TsfConstants.CK_PREFIX + "_afLinkCd"))) {
				if (TsfSession.getAttribute("isApp").equals("true")) { // 앱이면
					if (TsfSession.getAttribute("osType").equals("A")) {
						afLinkCd = "AF016"; // AOS앱
					} else if (TsfSession.getAttribute("osType").equals("I")) {
						afLinkCd = "AF017"; // IOS앱
					}
				} else { // 웹이면
					if (TsfSession.getFrontGb().equals("P")) {
						afLinkCd = "AF006"; // PC웹
					} else if (TsfSession.getFrontGb().equals("M")) {
						afLinkCd = "AF015"; // 모바일웹
					}
				}
			}
		}

		TsfSession.setAttribute("afLinkCd", afLinkCd);
		GagaCookieUtil.setCookie(response, TsfConstants.CK_PREFIX + "_afLinkCd", afLinkCd, -1);
		log.info("2.session's afLinkCd: {}", TsfSession.getAttribute("afLinkCd"));
		log.info("2.cookie's afLinkCd: {}", GagaCookieUtil.getCookie(request, TsfConstants.CK_PREFIX + "_afLinkCd"));

		try {
			if (StringUtils.isNotBlank(afLinkCd)) {
				String queryString = GagaStringUtil.convertParameterToQueryString(request.getParameterMap());
				if (StringUtils.isNotBlank(queryString)) {
					queryString = "?" + queryString;
				}

				InflowHst inflow = new InflowHst();
				inflow.setAfLinkCd(afLinkCd);
				inflow.setPageUrl(request.getRequestURL() + queryString);
				commonService.createInflowHistory(inflow);
			}
		} catch (Exception e) {
			// Do nothing
		}

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

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

}
