package org.holer.common.util;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import org.holer.common.model.HolerMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class IdleChecker
        extends IdleStateHandler {
    private static Logger log = LoggerFactory.getLogger(IdleChecker.class);


    public IdleChecker(int readerIdleTime, int writerIdleTime, int allIdleTime) {
        super(readerIdleTime, writerIdleTime, allIdleTime);
    }


    protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception {
        if (IdleStateEvent.FIRST_WRITER_IDLE_STATE_EVENT == evt) {

            log.debug("Channel write timeout {}.", ctx.channel());
            HolerMsg hmsg = new HolerMsg();
            hmsg.setType((byte) 7);
            ctx.channel().writeAndFlush(hmsg);
        } else if (IdleStateEvent.FIRST_READER_IDLE_STATE_EVENT == evt) {

            log.warn("Channel read timeout {}.", ctx.channel());
            ctx.channel().close();
        }
        super.channelIdle(ctx, evt);
    }
}
