package com.sv.netty.netty;

import com.sv.netty.utils.CommonUtils;
import com.sv.netty.utils.JsonUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;


/**
 * 自定义消息编码器
 *
 * @Author peakren
 * @Date 07/05/2017 10:43 PM
 */
public class MessageEncoder extends MessageToByteEncoder<Object> {

    private final static int MESSAGE_LENGTH = 4;
    private final static int MESSAGE_SEQNO = 8;
    private final static int MESSAGE_HEAD = 4;
    private final static String mSeqno = "doll";
    private final static int MAGIC_WORD = 0x9DDD;

    private static Logger logger = LoggerFactory.getLogger(MessageEncoder.class);

    Charset charset = Charset.forName("UTF-8");

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        String message = JsonUtils.encode(msg);
        logger.info("send message content:" + message);
        byte[] bodys = message.getBytes(charset.name());

        int len = bodys.length;
        out.writeInt(MAGIC_WORD);  //发送预留数据字节码
        out.writeInt(len); //发送head字节码
        out.writeBytes(bodys); //发送消息内容
    }

    byte[] getIntBytes(int crc) {
        byte[] targets = new byte[4];
        targets[0] = (byte) (crc & 0xff);
        targets[1] = (byte) ((crc >> 8) & 0xff);
        targets[2] = (byte) ((crc >> 16) & 0xff);
        targets[3] = (byte) (crc >> 24);
        return targets;
    }

    byte[] getLongBytes(long crc) {
        byte[] targets = new byte[8];
        targets[0] = (byte) (crc & 0xff);
        targets[1] = (byte) ((crc >> 8) & 0xff);
        targets[2] = (byte) ((crc >> 16) & 0xff);
        targets[3] = (byte) (crc >> 24 & 0xff);
        targets[4] = (byte) (crc >> 32 & 0xff);
        targets[5] = (byte) (crc >> 40 & 0xff);
        targets[6] = (byte) (crc >> 48 & 0xff);
        targets[7] = (byte) (crc >> 56);
        return targets;
    }

}
