package com.tourism.webadmin.ws.intercept;

import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
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 java.util.Map;

public class SystemMessageInterceptor implements HandshakeInterceptor {
    private ApplicationContext applicationContext;
    public SystemMessageInterceptor(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest){
            ServletServerHttpRequest httpRequest = (ServletServerHttpRequest) request;
            String userId = httpRequest.getServletRequest().getParameter("token");
            if (StringUtils.isBlank(userId)){
                return false;
            }
//            AESUtils bean = this.applicationContext.getBean(AESUtils.class);
//            String decrypt = bean.decrypt(userId);
            attributes.put("userId", userId);
            return true;
        }
        return false;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
