package com.github.msemys.esjc.tcp.handler;

import com.github.msemys.esjc.tcp.TcpCommand;
import com.github.msemys.esjc.tcp.TcpPackage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Duration;
import java.util.UUID;
import java.util.concurrent.ScheduledFuture;

import static java.util.concurrent.TimeUnit.MILLISECONDS;

public class HeartbeatHandler extends SimpleChannelInboundHandler<TcpPackage> {
    private static final Logger logger = LoggerFactory.getLogger(HeartbeatHandler.class);

    private final long timeoutMillis;
    private ScheduledFuture<?> timeoutTask;
    private final Object timeoutTaskLock = new Object();

    public HeartbeatHandler(Duration timeout) {
        timeoutMillis = timeout.toMillis();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TcpPackage msg) throws Exception {
        switch (msg.command) {
            case HeartbeatRequestCommand:
                ctx.writeAndFlush(TcpPackage.newBuilder()
                    .command(TcpCommand.HeartbeatResponseCommand)
                    .correlationId(msg.correlationId)
                    .build());
                break;
            case HeartbeatResponseCommand:
                cancelTimeoutTask();
                break;
            default:
                ctx.fireChannelRead(msg);
        }
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        cancelTimeoutTask();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        synchronized (timeoutTaskLock) {
            if (evt instanceof IdleStateEvent && timeoutTask == null) {
                ctx.writeAndFlush(TcpPackage.newBuilder()
                    .command(TcpCommand.HeartbeatRequestCommand)
                    .correlationId(UUID.randomUUID())
                    .build());
                timeoutTask = ctx.executor().schedule(() -> {
                    logger.info("Closing TCP connection [{}, L{}] due to HEARTBEAT TIMEOUT.", ctx.channel().remoteAddress(), ctx.channel().localAddress());
                    ctx.close();
                }, timeoutMillis, MILLISECONDS);
            }
        }
    }

    private void cancelTimeoutTask() {
        synchronized (timeoutTaskLock) {
            if (timeoutTask != null) {
                timeoutTask.cancel(true);
                timeoutTask = null;
            }
        }
    }

}

@@ -1723,32 +1723,81 @@
 ows Exception %7B%0A
+        if (evt instanceof IdleStateEvent) %7B%0A    
         synchron
@@ -1837,45 +1837,16 @@
     
+    
 if (
-evt instanceof IdleStateEvent && 
 time
@@ -1872,32 +1872,36 @@
                 
+    
 ctx.writeAndFlus
@@ -1918,32 +1918,36 @@
 ge.newBuilder()%0A
+    
                 
@@ -2007,32 +2007,36 @@
                 
+ 
+   
 .correlationId(U
@@ -2065,32 +2065,36 @@
                 
+    
 .build());%0A     
@@ -2096,32 +2096,36 @@
                 
+ 
+   
 timeoutTask = ct
@@ -2150,24 +2150,28 @@
 ule(() -%3E %7B%0A
+    
             
@@ -2330,24 +2330,28 @@
             
+    
 ctx.close();
@@ -2347,24 +2347,28 @@
 tx.close();%0A
+    
             
@@ -2404,16 +2404,34 @@
 CONDS);%0A
+                %7D%0A
         

synchronize on 'IdleStateEvent' only