package com.zanxiang.game.module.manage.config;

import com.zanxiang.game.module.manage.constant.RedisKeyConstant;
import com.zanxiang.game.module.manage.websocket.KfMsgRedisListener;
import com.zanxiang.game.module.manage.websocket.KfMsgWebsocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

/**
 * @author : lingfeng
 * @time : 2024-02-23
 * @description : 客服消息WebSocket配置
 */
@Configuration
@EnableWebSocket
public class KfMsgWebSocketConfig implements WebSocketConfigurer {

    private final KfMsgWebsocketHandler kfMsgWebsocketHandler;

    private final KfMsgRedisListener kfMsgRedisListener;

    @Autowired
    public KfMsgWebSocketConfig(KfMsgWebsocketHandler kfMsgWebsocketHandler, KfMsgRedisListener kfMsgRedisListener) {
        this.kfMsgWebsocketHandler = kfMsgWebsocketHandler;
        this.kfMsgRedisListener = kfMsgRedisListener;
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(kfMsgWebsocketHandler, "/api/kf/msg").setAllowedOrigins("*");
    }

    @Bean
    public RedisMessageListenerContainer redisContainer(RedisConnectionFactory connectionFactory) {
        MessageListenerAdapter listenerAdapter = new MessageListenerAdapter(kfMsgRedisListener, "onMessage");
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(listenerAdapter, new PatternTopic(RedisKeyConstant.KF_MSG_REDIS_LISTEN_TOPIC));
        return container;
    }
}
