package com.wecloud.im.netty.core;

import com.wecloud.im.netty.handler.NettyApiRequest;
import com.wecloud.im.ws.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.slf4j.Logger;
import org.slf4j.LoggerFactory;
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();
        }
    }

    /**
     * 发送错误信息
     *
     * @param ctx
     */
//    private void sendBad(ChannelHandlerContext ctx) {
//        String result = null;
//
//        try {
//            result = JsonUtil.obj2Json(ResultModel.error(ResultStatus.REQUEST_ERROR));
//        } catch (IOException ex) {
//            ex.printStackTrace();
//        }
//        FullHttpRequestUtils.send(ctx, result, HttpResponseStatus.OK);
//    }

    /**
     * 建立连接时，返回消息
     */
    @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 {
        Long clientId = ctx.channel().attr(ChannelManager.CLIENT_ID).get();
        log.info("触发channelInactive方法 clientId {}", clientId);
        super.channelInactive(ctx);
        if (clientId == null) {
            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);
    }
}
