package com.imdroid.vermgr.service;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class VersionHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        Channel channel = ctx.channel();
        UpgradeManager.INSTANCE.onChannelActive(channel);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;

            if (event.state() == IdleState.READER_IDLE) {
                Channel channel = ctx.channel();
                log.info(channel.remoteAddress() + " idle too long to be closed");
                channel.close();
            }
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx,
                            Object msg) throws Exception{
        Channel channel = ctx.channel();
        UpgradeManager.INSTANCE.onRxData(channel, (byte[]) msg);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx)
            throws Exception {
        Channel channel = ctx.channel();
        UpgradeManager.INSTANCE.onChannelInactive(channel);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();

        ctx.close();
    }
}
