package com.ym.im.core;


/**
 * @author: JJww
 * 对象解码器
 * @Date:2019-05-17
 */

import com.ym.im.entity.ChatRecord;
import com.ym.im.entity.MsgBody;
import com.ym.im.util.JsonUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

/**
 * @author: JJww
 * 对象解码器
 * @Date:2019-11-21
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class MessageDecoder extends MessageToMessageDecoder<TextWebSocketFrame> {

    @Override
    protected void decode(ChannelHandlerContext ctx, TextWebSocketFrame textWebSocketFrame, List out) throws Exception {

        final String jsonStr = textWebSocketFrame.text();
        MsgBody<ChatRecord> msgBody = new MsgBody<ChatRecord>().setCode(MsgBody.ERROR);
        try {
            msgBody = JsonUtils.json2Obj(jsonStr, MsgBody.class, ChatRecord.class);
        } catch (IOException e) {
            log.error("Json转{}异常：\r\n" + "Json原串：{}\r\n" + "===异常栈信息===", "MsgBody.class", jsonStr, e);
            msgBody.setCode(MsgBody.ERROR);
            msgBody.setMessage("错误的Json格式：" + jsonStr);
            ctx.channel().writeAndFlush(msgBody);
            return;
        }
        out.add(msgBody);
    }
}