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.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.TsfGoodsService;
import com.style24.front.biz.service.TsfRecentlyGoodsService;
import com.style24.front.support.env.TsfConstants;

import lombok.extern.slf4j.Slf4j;

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

/**
 * 상품뷰 Interceptor
 *
 * @author gagamel
 * @since 2020. 9. 11
 */
@Component
@Slf4j
public class TsfGoodsViewInterceptor extends HandlerInterceptorAdapter {

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

	@Autowired
	private TsfGoodsService goodsService;

	@Autowired
	private TsfRecentlyGoodsService recentlyGoodsService;

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

		try {
			// 상품뷰이력 생성
			goodsService.createGoodsViewHst(params.getString("goodsCd"), params.getString("ithrCd"));

			// 최근본상품 생성
			recentlyGoodsService.createRecentlyGoods(params.getString("goodsCd"));
		} catch (Exception e) {
			// Do nothing
		}

		// SSL Server
		boolean isSslServer = Boolean.parseBoolean(hasSsl);
		log.debug("isSslServer: [{}]", isSslServer);

		if (isSslServer) {
			// 상품유입경로 쿠키 설정
			GagaCookieUtil.setSecureCookie(response, TsfConstants.CK_PREFIX + "_ithrCd", params.getString("ithrCd"), -1);

			// 컨텐츠위치코드 쿠키 설정
			GagaCookieUtil.setSecureCookie(response, TsfConstants.CK_PREFIX + "_contentsLoc", params.getString("contentsLoc"), -1);
		} else {
			// 상품유입경로 쿠키 설정
			GagaCookieUtil.setCookie(response, TsfConstants.CK_PREFIX + "_ithrCd", params.getString("ithrCd"), -1);

			// 컨텐츠위치코드 쿠키 설정
			GagaCookieUtil.setCookie(response, TsfConstants.CK_PREFIX + "_contentsLoc", params.getString("contentsLoc"), -1);
		}

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

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

}
