package com.wecloud.im.netty.core;

import com.wecloud.im.netty.handler.NettyApiRequest;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.net.InetAddress;


@Component
@ChannelHandler.Sharable
public class ChannelInboundHandler extends ChannelInboundHandlerAdapter {
    private final Logger logger = LoggerFactory.getLogger(ChannelInboundHandler.class);
    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) {
            logger.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 (logger.isDebugEnabled()) {
            logger.debug("连接的客户端地址:{}", ctx.channel().remoteAddress());
        }
        ctx.writeAndFlush("客户端" + InetAddress.getLocalHost().getHostName() + "成功与服务端建立连接！ ");
        super.channelActive(ctx);
    }


}
