package com.cm.socket.encoder;

import com.cm.socket.pojo.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.CharsetUtil;
import org.apache.commons.lang3.StringUtils;

import java.nio.charset.Charset;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: MessageEncoder
 * @Description: 消息编码器
 * @Author: WangGeng
 * @Date: 2020/7/4 15:55
 * @Version: 1.0
 **/
public class MessageEncoder extends MessageToByteEncoder<Message> {

    @Override
    protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) throws Exception {
        byte[] tokenBytes = StringUtils.isBlank(msg.getToken()) ? new byte[0] : msg.getToken().getBytes(CharsetUtil.UTF_8);
        byte[] contentBytes = StringUtils.isBlank(msg.getContent()) ? new byte[0] : msg.getContent().getBytes(CharsetUtil.UTF_8);
        out.writeByte(msg.getStart());
        out.writeByte(msg.getType());
        out.writeInt(tokenBytes.length);
        out.writeInt(contentBytes.length);
        out.writeBytes(tokenBytes);
        out.writeBytes(contentBytes);
    }

}
