package com.mogo.telematic.client.handler

import com.mogo.telematic.MogoProtocolMsg
import com.mogo.telematic.MogoProtocolMsg.HEART_DATA
import com.mogo.telematic.client.listener.NettyClientListener
import com.mogo.telematic.client.status.ConnectState
import io.netty.channel.ChannelFuture
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInboundHandlerAdapter
import io.netty.handler.timeout.IdleStateEvent

class HeartbeatHandler(val listener: NettyClientListener<*>): ChannelInboundHandlerAdapter() {

    private val heartbeatData by lazy {
        MogoProtocolMsg(HEART_DATA, 1, byteArrayOf(0x0))
    }

    override fun userEventTriggered(ctx: ChannelHandlerContext?, evt: Any?) {
        if (evt is IdleStateEvent) {
            ctx?.channel()?.writeAndFlush(heartbeatData)?.addListener { future ->
                if (future is ChannelFuture) {
                    if (!future.isSuccess) {
                        listener.onClientStatusConnectChanged(
                            ConnectState.STATUS_CONNECT_CLOSED,
                            "channelInactive",
                            ctx.channel()
                        )
                        future.channel().close()
                    }
                }
            }
        } else {
            super.userEventTriggered(ctx, evt)
        }
    }
}