package com.yingying.tourist.request;

import com.alibaba.fastjson.JSONObject;
import com.yingying.tourist.common.UrlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.util.WebUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

//@Component
//@Order(2)
//@WebFilter(filterName = "SessionFilter", urlPatterns = "/*")
@Slf4j
public class SessionFilter implements Filter {

	@Value("${session.domain}")private String COOKIEDOMAIN;

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// 检查sessionId的cookie是否存在,不存在即为新连接，需要初始化sessionId到cookie中
		checkRemoteSession((HttpServletRequest) request, (HttpServletResponse) response);
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	private void checkRemoteSession(HttpServletRequest request, HttpServletResponse response) {
		String sessionKey = null;
		String token = request.getParameter("token");
		log.info("token------>>>first:[{}]",token);
        if (StringUtils.isEmpty(token)) {
            String payload = UrlUtils.getRequestPayload(request);
            if (!StringUtils.isEmpty(payload)) {
                JSONObject jsonObject = JSONObject.parseObject(payload);
                token = jsonObject.getString("token");
            }
        }
		
		if (StringUtils.isNotEmpty(token)) {
			sessionKey = token;
			log.info("sessionKey------>>>second:[{}]",sessionKey);
		} else {
			Cookie sessionKeyCookie = WebUtils.getCookie(request, SessionAuthorization.SESSION_KEY_COOKIE_NAME);
			if (sessionKeyCookie == null) {
				sessionKey = UUID.randomUUID().toString();
				sessionKeyCookie = new Cookie(SessionAuthorization.SESSION_KEY_COOKIE_NAME, sessionKey);
			} else {
				sessionKey = sessionKeyCookie.getValue();
			}
			log.info("sessionKey------>>>third:[{}]",sessionKey);
			sessionKeyCookie.setPath("/");
			sessionKeyCookie.setDomain(COOKIEDOMAIN);
			sessionKeyCookie.setMaxAge(SessionAuthorization.DEFAULT_SESSION_COOKIE_EXPIRE);
			sessionKeyCookie.setHttpOnly(true);
			response.addCookie(sessionKeyCookie);
		}
		RequestSessionKey.putSessionKey(sessionKey);
	}
	
}