package com.hdkj.lt.core.ws.config;

import com.hdkj.lt.base.constants.SystemGlobalConstant;
import com.hdkj.lt.core.ws.interceptor.ServletWebSocketInterceptor;
import com.hdkj.lt.core.ws.handler.AbstractDefaultWebSocketHandler;
import com.hdkj.lt.core.hussar.SpringContextHolder;
import org.reflections.Reflections;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.handler.ExceptionWebSocketHandlerDecorator;

import java.util.Set;

/**
 * @Description:
 * @Author: wenhao
 * @Create: 2024/04/26 11:03
 * @Version: 1.0
 */
@EnableWebSocket
@Configuration(proxyBeanMethods = false)
public class WebSocketConfiguration implements WebSocketConfigurer {

    public static final String SESSION_KEY = "sessionKey";

    @Override
    public void registerWebSocketHandlers(@NonNull WebSocketHandlerRegistry registry) {
        // 反射取当前服务下所有的websocket处理器资源（需要继承AbstractDefaultWebSocketHandler）进行服务注册
        Reflections reflections = new Reflections(SystemGlobalConstant.BIZMS_BASE_PACKAGE);
        Set<Class<? extends AbstractDefaultWebSocketHandler>> handlerClasses = reflections.getSubTypesOf(AbstractDefaultWebSocketHandler.class);
        for (Class<? extends AbstractDefaultWebSocketHandler> handlerClass : handlerClasses) {
            AbstractDefaultWebSocketHandler handler = SpringContextHolder.getBean(handlerClass);
            ServletWebSocketInterceptor handshakeInterceptor = new ServletWebSocketInterceptor();
            registry.addHandler(new ExceptionWebSocketHandlerDecorator(handler), handler.getPath())
                    .addInterceptors(handshakeInterceptor)
                    .setAllowedOrigins("*"); //跨域设置
            // withSockJS为了兼容sockjs，因为有些浏览器不支持WebSocket协议
            registry.addHandler(new ExceptionWebSocketHandlerDecorator(handler), "/sockjs" + handler.getPath())
                    .addInterceptors(handshakeInterceptor)
                    .setAllowedOrigins("*") //跨域设置
                    .withSockJS();
        }
    }

    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(Runtime.getRuntime().availableProcessors());
        scheduler.setRemoveOnCancelPolicy(true);
        scheduler.initialize();
        return scheduler;
    }

}
