package org.example.socket.utils;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

/**
 * @author zjb
 * @since 2023-12-11 10:49:32
 */
public class MyEncoder extends ChannelOutboundHandlerAdapter {

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        // 对消息进行编码
        ByteBuf encodedMsg = encode2(msg);
        // 将编码后的消息发送到下一个 ChannelHandler
        ctx.write(encodedMsg, promise);
    }

    // 自定义的编码方法
    private ByteBuf encode(Object msg) throws DecoderException {
        // 实现编码逻辑
        ByteBuf buf = Unpooled.buffer();
        buf.writeBytes(Hex.decodeHex(msg.toString().replaceAll(" ", "").toCharArray()));
        return buf;
    }

    //编码 十进制数组编码
    private ByteBuf encode2(Object msg) throws DecoderException {
// 创建一个新的ByteBuf对象
        ByteBuf byteBuf = Unpooled.buffer();
        // 遍历数组并写入到ByteBuf中
        for (int i : (int [])msg) {
            byteBuf.writeByte(i);
        }
        return byteBuf;
    }

}
