package org.dromara.netty;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.DefaultAddressedEnvelope;
import io.netty.handler.codec.MessageToMessageEncoder;

import java.net.SocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.List;


public class Encode extends MessageToMessageEncoder {

    @Override
    public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) throws Exception {
        super.connect(ctx, remoteAddress, localAddress, promise);
    }

    @Override
    public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
        super.disconnect(ctx, promise);
    }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        super.write(ctx, msg, promise);
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, List out) throws Exception {
        //该处返回空 改由主动发送
        try {

            if(msg==null || StrUtil.isEmptyIfStr(msg)){
                ByteBuf buf = Unpooled.copiedBuffer("".getBytes(CharsetUtil.UTF_8));
                out.add(buf);
                return;
            }
            if(msg instanceof DefaultAddressedEnvelope){
                if(((DefaultAddressedEnvelope<?, ?>) msg).content() instanceof byte[]){
                    out.add(Unpooled.copiedBuffer((byte[]) ((DefaultAddressedEnvelope<?, ?>) msg).content()));
                }else{
                    out.add(Unpooled.copiedBuffer(((DefaultAddressedEnvelope<?, ?>) msg).content().toString().getBytes(StandardCharsets.UTF_8)));
                }
            } else if(msg instanceof ByteBuf){
                out.add(Unpooled.copiedBuffer((ByteBuf) msg));
            }else{
                ByteBuf buf = Unpooled.copiedBuffer("".getBytes(CharsetUtil.UTF_8));
                out.add(buf);
            }
        }catch (Exception e){}

    }
}


