package cn.reghao.tnb.message.app.ws.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author reghao
 * @date 2022-03-11 16:42:44
 */
@Slf4j
@Component
public class WebSocketInterceptor implements HandshakeInterceptor {
    @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 path = httpRequest.getURI().getPath();
            if (path.startsWith(WebSocketPath.wsMedia)) {
                HttpServletRequest httpServletRequest = httpRequest.getServletRequest();
                String userToken = httpServletRequest.getParameter("userToken");
                String videoId = httpServletRequest.getParameter("videoId");
                if (userToken != null && videoId != null) {
                    attributes.put("userToken", userToken);
                    attributes.put("videoId", videoId);
                    return true;
                }

                log.error("connect to {} error", WebSocketPath.wsMedia);
                return false;
            } else if (path.startsWith(WebSocketPath.wsChat)) {
                HttpServletRequest httpServletRequest = httpRequest.getServletRequest();
                String userToken = httpServletRequest.getParameter("userToken");
                if (userToken != null) {
                    attributes.put("userToken", userToken);
                    return true;
                }

                log.error("connect to {} error", WebSocketPath.wsChat);
                return false;
            } else if (path.startsWith(WebSocketPath.wsDevice)) {
                HttpServletRequest httpServletRequest = httpRequest.getServletRequest();
                String deviceId = httpServletRequest.getParameter("deviceId");
                if (deviceId != null) {
                    attributes.put("deviceId", deviceId);
                    return true;
                }

                log.error("connect to {} error", WebSocketPath.wsDevice);
                return false;
            }
        }

        return true;
    }

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