package com.docus.server.common.netty.server.handler;

import com.docus.core.util.json.JSON;
import com.docus.server.common.CommMsg;
import com.fasterxml.jackson.core.type.TypeReference;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.Date;

public class EchoServerHandler extends ChannelInboundHandlerAdapter {


    //客户端连接上来，没有心跳前，属于离线状态，有心跳后，才属于在线状态。
    //客户端断开后，自动剔除，agent。
    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelRegistered();
        Channel incoming = ctx.channel();
        System.out.println("NettyClient:" + incoming.remoteAddress() + "在线1");
    }


    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelUnregistered();
        Channel incoming = ctx.channel();
        System.out.println("NettyClient:" + incoming.remoteAddress() + "在线2");
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelActive();
        Channel incoming = ctx.channel();
        System.out.println("NettyClient:" + incoming.remoteAddress() + "在线3");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            ByteBuf buf = (ByteBuf) msg;
            //创建目标大小的数组
            byte[] barray = new byte[buf.readableBytes()];
            //把数据从bytebuf转移到byte[]
            buf.getBytes(0, barray);
            //将byte[]转成字符串用于打印
            String str = new String(barray);

            CommMsg<TerminatorContent> commMsg = JSON.fromJSONWithGeneric(str, new TypeReference<CommMsg<TerminatorContent>>() {
            });

            if (str.length() > 0) {
                System.out.println(str);
                System.out.println("收到消息回复一条消息给客户端");
                System.out.println("client channelActive..");
                ctx.writeAndFlush(Unpooled.copiedBuffer("服务器端发一条数据给客户端" + new Date().toString(), CharsetUtil.UTF_8)); // 必须有flush
                System.out.flush();
            } else {
                System.out.println("不能读啊");
            }
        } finally {
        }
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("server occur exception:" + cause.getMessage());
        cause.printStackTrace();
        ctx.close(); // 关闭发生异常的连接
    }
}
