import { server } from '../index';
import { playerManager } from '../managers/PlayerManager';

/**
 * 广播消息给所有在线玩家
 * @param msgName 消息名称
 * @param msg 消息内容
 * @param excludeConnectionId 排除的连接ID（可选，用于排除发送者自己）
 */
export function broadcastToAll<T>(msgName: string, msg: T, excludeConnectionId?: string): void {
    const onlinePlayers = playerManager.getOnlinePlayers();
    const targetConns = [];
    
    for (const player of onlinePlayers) {
        const connectionId = playerManager.getPlayerConnectionId(player.id);
        
        if (!connectionId) {
            continue;
        }
        
        // 如果指定了排除的连接ID，跳过该连接
        if (excludeConnectionId && connectionId === excludeConnectionId) {
            continue;
        }
        
        const conn = server.connections.find(c => c.id === connectionId);
        if (conn) {
            targetConns.push(conn);
        }
    }
    
    // 使用 broadcastMsg 批量发送，只执行一次序列化
    if (targetConns.length > 0) {
        (server as any).broadcastMsg(msgName, msg, targetConns);
    }
}

/**
 * 广播消息给指定玩家
 * @param playerId 玩家ID
 * @param msgName 消息名称
 * @param msg 消息内容
 */
export function broadcastToPlayer<T>(playerId: string, msgName: string, msg: T): void {
    const connectionId = playerManager.getPlayerConnectionId(playerId);
    
    if (!connectionId) {
        return;
    }
    
    const conn = server.connections.find(c => c.id === connectionId);
    if (conn) {
        (conn as any).sendMsg(msgName, msg);
    }
}

/**
 * 广播消息给多个玩家
 * @param playerIds 玩家ID列表
 * @param msgName 消息名称
 * @param msg 消息内容
 */
export function broadcastToPlayers<T>(playerIds: string[], msgName: string, msg: T): void {
    for (const playerId of playerIds) {
        broadcastToPlayer(playerId, msgName, msg);
    }
}
