package com.its.op.xnettcp.client.handler;

import com.its.utils.NettyUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
public class NettyTcpClientIdleHandler extends IdleStateHandler {

    public NettyTcpClientIdleHandler(long readerIdleTime, long writerIdleTime, long allIdleTime, TimeUnit unit) {
        super(readerIdleTime, writerIdleTime, allIdleTime, unit);
    }

    @Override
    protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) {
        String ipAddress = NettyUtils.getRemoteIpAddress(ctx.channel());
        log.warn("channelIdle: {}", ipAddress);
        // disconnect here
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        String ipAddress = NettyUtils.getRemoteIpAddress(ctx.channel());
        log.info("channelActive: {}", ipAddress);
        try {
            super.channelActive(ctx);
        } catch (IOException ie) {
            log.error("channelActive: IOException");
        } catch (Exception e) {
            log.error("channelActive: Exception");
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        String ipAddress = NettyUtils.getRemoteIpAddress(ctx.channel());
        log.warn("channelInactive: {}", ipAddress);
        try {
            super.channelInactive(ctx);
        } catch (IOException ie) {
            log.error("channelInactive: IOException");
        } catch (Exception e) {
            log.error("channelInactive: Exception");
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        String ipAddress = NettyUtils.getRemoteIpAddress(ctx.channel());
        log.error("exceptionCaught: {}, {}", ipAddress, cause.getMessage());

        ctx.channel().close();
    }
}
