package com.yushu.web.websocket;

import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.websocket.server.ServerContainer;
import jakarta.websocket.server.ServerEndpointConfig;

/**
 * WebSocket配置类
 */
@Configuration
public class WebSocketConfig {
    
    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(WebSocketConfig.class);
    
    /**
     * 注入ServerEndpointExporter
     * 这个bean会自动注册使用了@ServerEndpoint注解声明的WebSocket endpoint
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        log.info("[WebSocket] 正在配置ServerEndpointExporter");
        ServerEndpointExporter exporter = new ServerEndpointExporter();
        log.info("[WebSocket] ServerEndpointExporter配置完成");
        return exporter;
    }
    
    /**
     * 手动注册WebSocket端点（用于调试）
     */
    @Bean
    public ServletContextInitializer webSocketServletContextInitializer() {
        return new ServletContextInitializer() {
            @Override
            public void onStartup(ServletContext servletContext) throws ServletException {
                try {
                    log.info("[WebSocket] 开始手动注册WebSocket端点");
                    
                    ServerContainer serverContainer = (ServerContainer) servletContext.getAttribute(ServerContainer.class.getName());
                    if (serverContainer != null) {
                        log.info("[WebSocket] 找到ServerContainer: {}", serverContainer.getClass().getName());
                        
                        // 注册简单测试端点
                        serverContainer.addEndpoint(SimpleWebSocketServer.class);
                        log.info("[WebSocket] 已注册SimpleWebSocketServer: /ws/test");
                        
                        // 注册消息端点
                        ServerEndpointConfig config = ServerEndpointConfig.Builder
                            .create(MessageWebSocketServer.class, "/ws/message")
                            .configurator(new MessageWebSocketConfigurator())
                            .build();
                        serverContainer.addEndpoint(config);
                        log.info("[WebSocket] 已注册MessageWebSocketServer: /ws/message");
                        
                    } else {
                        log.error("[WebSocket] 未找到ServerContainer");
                    }
                } catch (Exception e) {
                    log.error("[WebSocket] 手动注册WebSocket端点失败", e);
                }
            }
        };
    }
}



