package com.fizz.business.interceptor;

import com.fizz.business.constants.enums.WsTypeEnum;
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.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;
import java.util.Objects;

@Slf4j
@Component
public class TrackWsInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        try {
            String type = ((ServletServerHttpRequest) request).getServletRequest().getParameter("type");
            if (Objects.isNull(WsTypeEnum.getByValue(type))) {
                log.error("[websocket]beforeHandshake error: type={}", type);
                return false;
            }
            attributes.put("type", type);
            return true;
        } catch (Exception e) {
            log.error("[websocket]beforeHandshake error", e);
            return false;
        }

    }

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

    }
}