package com.vetti.socket.util;

import javax.websocket.Session;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.concurrent.*;

/**
 * 音频自动发送
 */
public class AudioHub {

    private static final Map<String, ConcurrentLinkedQueue<ByteBuffer>> userQueues = new ConcurrentHashMap<>();

    static {
        // 20ms 调度推流线程
        new Thread(() -> {
            while (true) {

                for (Map.Entry<String, ConcurrentLinkedQueue<ByteBuffer>> entry : userQueues.entrySet()) {
                    String sessionId = entry.getKey();
                    ConcurrentLinkedQueue<ByteBuffer> queue = entry.getValue();

                    ByteBuffer frame = queue.poll();
                    if (frame != null) {
                        Session s = SessionManager.get(sessionId);
                        if (s != null && s.isOpen()) {
                            s.getAsyncRemote().sendBinary(frame);
                        }
                    }
                }

                try { Thread.sleep(20); } catch (Exception ignore) {}
            }
        }).start();
    }

    public static void addClient(Session session) {
        userQueues.put(session.getId(), new ConcurrentLinkedQueue<>());
        SessionManager.add(session);
    }

    public static void removeClient(Session session) {
        userQueues.remove(session.getId());
        SessionManager.remove(session.getId());
    }

    public static void pushToClient(String sessionId, ByteBuffer frame) {
        if (userQueues.containsKey(sessionId)) {
            userQueues.get(sessionId).add(frame);
        }
    }
}
