package com.ruoyi.ws.service;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.Session;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSON;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class DeviceWebSocketService {
    
    // MAC地址到Session集合的映射
    private static final Map<String, Set<Session>> MAC_TO_SESSIONS = new ConcurrentHashMap<>();
    
    /**
     * 添加设备WebSocket会话的MAC地址
     */
    public void addMacToSession(String mac, Session session) {
        if (mac == null || session == null) {
            return;
        }

        // 添加MAC到Session的映射
        Set<Session> sessions = MAC_TO_SESSIONS.computeIfAbsent(mac, k -> new HashSet<>());
        synchronized (sessions) {
            sessions.add(session);
        }
        
        log.info("Session添加MAC地址{}成功，当前Session关联的MAC地址数量：{}", mac, sessions.size());
    }

    /**
     * 从Session中移除指定的MAC地址
     */
    public void removeMacFromSession(String mac, Session session) {
        if (mac == null || session == null) {
            return;
        }

        // 从MAC到Session的映射中移除
        Set<Session> sessions = MAC_TO_SESSIONS.get(mac);
        if (sessions != null) {
            synchronized (sessions) {
                sessions.remove(session);
                if (sessions.isEmpty()) {
                    MAC_TO_SESSIONS.remove(mac);
                }
            }
        }
        
        log.info("从Session中移除MAC地址{}成功", mac);
    }

    /**
     * 移除设备WebSocket会话
     */
    public void removeSession(Session session) {
        if (session == null) {
            return;
        }

        // 遍历所有MAC地址,移除对应的session
        for (Map.Entry<String, Set<Session>> entry : MAC_TO_SESSIONS.entrySet()) {
            String mac = entry.getKey();
            Set<Session> sessions = entry.getValue();
            if (sessions != null) {
                synchronized (sessions) {
                    sessions.remove(session);
                    if (sessions.isEmpty()) {
                        MAC_TO_SESSIONS.remove(mac);
                    }
                }
            }
        }

        log.info("WebSocket会话已移除");
    }

    /**
     * 获取MAC地址关联的所有WebSocket会话
     */
    public Set<Session> getSessions(String mac) {
        if (mac == null) {
            return new HashSet<>();
        }
        Set<Session> sessions = MAC_TO_SESSIONS.get(mac);
        if (sessions == null) {
            return new HashSet<>();
        }
        synchronized (sessions) {
            return new HashSet<>(sessions);
        }
    }

    /**
     * 向指定MAC地址发送消息
     *
     * @param message 消息内容
     * @param macs 目标MAC地址数组
     */
    public void sendMessageToDevice(Object message, String... macs) {
        if (message == null) {
            return;
        }
        this.sendMessageToDevice(message, Arrays.asList(macs));
    }

    /**
     * 向指定MAC地址发送消息
     *
     * @param message 消息内容
     * @param macs 目标MAC地址集合
     */
    public void sendMessageToDevice(Object message, Collection<String> macs) {
        if (message == null) {
            return;
        }
        
        String msg = JSON.toJSONString(message);
        for (String mac : macs) {
            Set<Session> sessions = this.getSessions(mac);
            for (Session session : sessions) {
                if (session != null) {
                    try {
                        if (session.isOpen()) {
                            session.getBasicRemote().sendText(msg);
                            log.info("向MAC地址{}发送消息成功: {}", mac, msg);
                        }
                    } catch (Exception e) {
                        log.error("发送消息给MAC地址{}失败", mac, e);
                    }
                }
            }
        }
    }
    
}
