package com.signal.sig.ws;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;

public class SigWebSocketClientMap {
	private static ConcurrentMap<String, ChannelHandlerContext> SIG_CHANNEL_MAP;

	public static ConcurrentMap<String, ChannelHandlerContext> getInstance() {
		if(SIG_CHANNEL_MAP == null) {
			SIG_CHANNEL_MAP = new ConcurrentHashMap<>();
		}

		return SIG_CHANNEL_MAP;
	}

	public static void sendBroadCast(String msg) {
		
		System.out.println("SigWebSocketClientMap::receive message : " + msg);
		
		ConcurrentMap<String, ChannelHandlerContext> channelMap = SigWebSocketClientMap.getInstance();
		System.out.println("SigWebSocketClientMap::sendBroadCast: " + channelMap.size());
		
		Set<String> keySets = channelMap.keySet();
        for(String key : keySets) {
            WebSocketFrame wsf = new TextWebSocketFrame(msg);
            ChannelHandlerContext ctx = channelMap.get(key);
            // Event send to next event handler
            System.out.println("SigWebSocketClientMap::sendBroadCast: " + ctx.toString());
            ctx.fireChannelActive();
            ctx.channel().writeAndFlush(wsf);
        }
	}

	private SigWebSocketClientMap() {

	}
}
