package com.jpsoft.shinestar.lapi.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.SocketAddress;
import java.util.List;

@Slf4j
public class TextDecodeHandler extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) throws Exception {
        byteBuf.markReaderIndex();

        byte[] buffer = new byte[byteBuf.readableBytes()];

        for(int i=0;i<buffer.length;i++) {
            buffer[i] = byteBuf.readByte();
        }

        byteBuf.resetReaderIndex();

        String json = new String(buffer,"UTF-8");

        SocketAddress remoteAddress = ctx.channel().remoteAddress();

        log.warn(String.format("收到来自%s数据:%s",remoteAddress.toString(), json));
    }

    private void printRecvData(SocketAddress remoteAddress, ByteBuf byteBuf) {
        //打印接收到的数据
        byteBuf.markReaderIndex();
        StringBuilder sb = new StringBuilder();

        while (byteBuf.readableBytes()>0) {
            if (sb.length()>0){
                sb.append(" ");
            }

            short b = byteBuf.readUnsignedByte();

            //java中byte是-128~127，C#中是0~255，需要转化
            String str = Integer.toHexString(b);

            if (str.length()==1){
                sb.append("0");
            }

            sb.append(str.toUpperCase());
        }

        log.warn(String.format("收到来自%s数据(累计):%s",remoteAddress.toString(), sb.toString()));

        byteBuf.resetReaderIndex();
    }
}
