package com.cmvr.framework.websocket.handler;

import com.cmvr.framework.websocket.annotation.WSMessageType;
import com.cmvr.framework.websocket.enums.WSMessageTypeEnum;
import com.cmvr.framework.websocket.manager.ChannelSubscriptionManager;
import com.cmvr.framework.websocket.message.WSChannelSubscriptionMessage;
import com.cmvr.framework.websocket.service.GrpcClientService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.WebSocketSession;

import java.util.concurrent.CompletableFuture;

/**
 * 频道订阅消息处理
 */
@WSMessageType(value = WSMessageTypeEnum.CHANNEL_SUBSCRIPTION, messageClass = WSChannelSubscriptionMessage.class)
public class ChannelSubscriptionMessageHandler implements WSMessageHandler<WSChannelSubscriptionMessage> {
    private static final Logger log = LoggerFactory.getLogger(ChannelSubscriptionMessageHandler.class);
    @Autowired
    private ChannelSubscriptionManager channelSubscriptionManager;
    @Autowired
    private GrpcClientService grpcClientService;
    public void handle(WebSocketSession session, WSChannelSubscriptionMessage message) throws Exception {
        String action = message.getAction();
        String userId = session.getAttributes().get("userId").toString();
        // service/method/terminalId/deviceId
        String channel = message.getChannel();
        String[] channelInfoArr = channel.split("\\/");
        String service = channelInfoArr[0];
        String method = channelInfoArr[1];
        String terminalId = channelInfoArr[2];
        String deviceId = channelInfoArr[3];
        if ("subscribe".equals(action)) {
            if (!channelSubscriptionManager.hasSubscribers(channel)) {
                // 异步调用gRPC
                CompletableFuture.runAsync(() -> {
                    try {
                        grpcClientService.send(true, terminalId, deviceId, service, method);
                    } catch (Exception e) {
                        log.error("gRPC订阅失败: {}", e.getMessage());
                    }
                });
            }
            channelSubscriptionManager.subscribe(channel, session);
        } else if ("unsubscribe".equals(action)) {
            channelSubscriptionManager.unsubscribe(channel, session);
            if (!channelSubscriptionManager.hasSubscribers(channel)) {
                CompletableFuture.runAsync(() -> {
                    try {
                        grpcClientService.send(false, terminalId, deviceId, service, method);
                    } catch (Exception e) {
                        log.error("gRPC取消订阅失败: {}", e.getMessage());
                    }
                });
            }
        } else {
            System.out.println("未知频道操作: " + action);
            return;
        }

        // 统一记录日志
        log.info("用户{} {} 频道{}", userId, getActionDescription(action), channel);
    }

    // 根据动作获取描述文本
    private String getActionDescription(String action) {
        return "subscribe".equals(action) ? "订阅了" : "取消订阅了";
    }
}
