package com.wecloud.im.server.handler;

import com.wecloud.im.server.manager.ChannelManager;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Component;

import java.net.InetAddress;


@Component
@ChannelHandler.Sharable
@Slf4j
public class ChannelInboundHandler extends ChannelInboundHandlerAdapter {
    private final NettyApiRequest nettyApiRequest;

    public ChannelInboundHandler(NettyApiRequest nettyApiRequest) {
        this.nettyApiRequest = nettyApiRequest;
    }


    /**
     * 收到消息时，返回信息
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        FullHttpRequest httpRequest = (FullHttpRequest) msg;
        try {
            nettyApiRequest.handle(ctx, msg, httpRequest);
        } catch (Exception e) {
            log.error("SingleNettyServer处理请求失败!", e);
//            this.sendBad(ctx);
        } finally {
            //释放请求
            httpRequest.release();
        }
    }

    /**
     * 建立连接时，返回消息
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        if (log.isInfoEnabled()) {
            log.info("连接的客户端地址:{}", ctx.channel().remoteAddress());
        }
        ctx.writeAndFlush("客户端" + InetAddress.getLocalHost().getHostName() + "成功与服务端建立连接！ ");
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        Long clientId = ctx.channel().attr(ChannelManager.CLIENT_ID).get();
        log.info("触发channelInactive方法 clientId {}", clientId);
//        ctx.channel().close();
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        super.exceptionCaught(ctx, cause);
        Long clientId = ctx.channel().attr(ChannelManager.CLIENT_ID).get();
        log.info("触发exceptionCaught方法 clientId {}", clientId);
    }
}
