package com.signal.sig.ws;

import java.nio.charset.Charset;
import java.util.concurrent.ConcurrentMap;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
public class SigWebSocketClientHandler extends SimpleChannelInboundHandler<WebSocketFrame> {
 

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame msg) throws Exception {
        /*
         * 접속되어 있는 웹소켓클라이언트로 부터 데이터 수신하였을 경우
         */
    	String sMsg = ((ByteBuf) msg.content()).toString(Charset.defaultCharset());
    	System.out.println("SigWebSocketClientHandler::channelRead0: " + ctx + ", " + sMsg);
    	SigWebSocketClientMap.sendBroadCast(sMsg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    	/*
    	 * 웹소켓 클라이언트로 부터의 데이터 수신이 완료된 경우
    	 */
    	System.out.println("SigWebSocketClientHandler::channelReadComplete: " + ctx);
        ctx.flush();
    }

    @Override
   	public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
	    /*
	     * 웹소켓 클라이언트가 연결이 되고 프레임웍에 등록된 경우
	     */
    	ConcurrentMap<String, ChannelHandlerContext> channelMap = SigWebSocketClientMap.getInstance();
	   
    	channelMap.put(ctx.channel().id().toString(), ctx);
    	System.out.println("SigWebSocketClientHandler::channelRegistered: " + ctx + ", " + channelMap.size());
    	return;
   	}
 
    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
    	/*
    	 * 웹소켓 클라이언트가 연결 종료되고 프레임웍에서 제거된 경우
    	 */
 	   	ConcurrentMap<String, ChannelHandlerContext> channelMap = SigWebSocketClientMap.getInstance();

 	   	channelMap.remove(ctx.channel().id().toString());
    	System.out.println("SigWebSocketClientHandler::channelUnregistered: " + ctx + ", " + channelMap.size());
 	   
    	super.channelUnregistered(ctx);
    }
}
