package com.tsi.comm.server.tcp.handler;

import com.tsi.comm.server.tcp.service.ConnectionLifecycleService;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@RequiredArgsConstructor
@Component
@ChannelHandler.Sharable
public class CvimServerInboundMessageHandler extends ChannelInboundHandlerAdapter {

    private final ConnectionLifecycleService connectionService;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.connectionService.handleChannelActive(ctx);
        ctx.fireChannelActive();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        this.connectionService.handleChannelInactive(ctx);
        ctx.fireChannelInactive();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object e) throws Exception {
        if (e instanceof IdleStateEvent) {
            this.connectionService.handleIdleStateEvent(ctx, (IdleStateEvent) e);
        }
        ctx.fireUserEventTriggered(e);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        this.connectionService.handleExceptionCaught(ctx, cause);
        ctx.fireExceptionCaught(cause);
        ctx.channel().close();
    }
}
