package cn.com.ty.lift.push.websocket.config;

import cn.com.ty.lift.common.constants.ApiConstants;
import cn.com.ty.lift.push.websocket.dao.entity.User;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.util.Map;

public class WebSocketInterceptor implements HandshakeInterceptor {
	
	/**
	 * 进入handler之前的拦截
	 */
	@Override
	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler wsHandler, Map<String, Object> map) {

	    if(request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;
	    	HttpSession session = serverHttpRequest.getServletRequest().getSession();
            User user = (User) session.getAttribute(ApiConstants.CURRENT_USER);
            if(user != null) {
            	map.put(ApiConstants.CURRENT_USER_ID, user.getId());
            }
	    }
	    return true;
	}

	@Override
	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                               Exception exception) {
        ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;
    	HttpSession session = serverHttpRequest.getServletRequest().getSession();
        User user = (User) session.getAttribute(ApiConstants.CURRENT_USER);
        if(user != null) {
        	System.out.println("用户"+ user.getName() +"连接进入系统");
		} else {
			System.out.println("当前连接为空");
		}
	}

}
