package org.dromara.netty;

import cn.hutool.json.JSONUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.dromara.netty.pojo.NettyChannelHandlerContext;

import java.util.List;


public class Decode extends MessageToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, Object msg, List out) throws Exception {
        //收到的消息转成String

        try {
            byte[] bytes = null;
            if(ctx.channel() instanceof NioDatagramChannel){

                ByteBuf byteBuf = ((DatagramPacket) msg).content();
                bytes= new byte[byteBuf.readableBytes()];
                byteBuf.readBytes(bytes);
            }else{
                bytes = new byte[((ByteBuf) msg).readableBytes()];
                ((ByteBuf) msg).readBytes(bytes);
            }
            if(bytes.length>0){
                String msgdata =  JSONUtil.toJsonStr(bytes);
//                System.out.println("收到消息："+msgdata);
                out.add(msgdata);
            }
        }catch (Exception e){}finally {
            ctx.flush();
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        NettyChannelHandlerContextMapCache.ChannelMapCache.put(ctx.channel().toString(),new NettyChannelHandlerContext(ctx));
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);

        NettyChannelHandlerContextMapCache.ChannelMapCache.remove(ctx.channel().toString());
        ctx.channel().close();
    }

}
