package com.its.op.xnettcp.client.listener;

import com.its.op.xnettcp.client.NettyTcpClientVds;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RequiredArgsConstructor
public class NettyTcpClientConnectListener implements ChannelFutureListener {

    private final NettyTcpClientVds client;

    /**
     * 최초 서버와 접속이 실패할 경우 이벤트 핸들러
     * @param channelFuture
     * @throws Exception
     */
    @Override
    public void operationComplete(ChannelFuture channelFuture) {
        if (!channelFuture.isSuccess()) {
            // 연결이 안되었으므로 채널을 close 한다.
            // channel 을 close 하면 NettyTcpClientCloseListener 의 이벤트가 발생한다.
            log.warn("NettyTcpClientConnectListener:  !SUCCESS, {}, cause,{}", channelFuture.channel().toString(), channelFuture.cause().toString());
            channelFuture.channel().close();
            //channelFuture.channel().eventLoop().schedule(this.client, this.client.getReconnectTime(), TimeUnit.SECONDS);
        } else {
            log.info("NettyTcpClientConnectListener: SUCCESS, {}", channelFuture.channel().toString());
        }
/*
        if (channelFuture.isCancelled()) {
            log.error("NettyTcpClientConnectListener:  Canceled, {}, cause,{}", channelFuture.channel().toString(), channelFuture.cause().toString());
            channelFuture.channel().close();
            channelFuture.channel().eventLoop().schedule(this.client, this.client.getReconnectTime(), TimeUnit.SECONDS);
        } else if (!channelFuture.isSuccess()) {
            log.error("NettyTcpClientConnectListener:  !Success, {}, cause,{}", channelFuture.channel().toString(), channelFuture.cause().toString());
            channelFuture.channel().close();
            channelFuture.channel().eventLoop().schedule(this.client, this.client.getReconnectTime(), TimeUnit.SECONDS);
        } else if (!channelFuture.channel().isActive()) {
            log.error("NettyTcpClientConnectListener:  !Active, {}, cause,{}", channelFuture.channel().toString(), channelFuture.cause().toString());
            channelFuture.channel().close();
            channelFuture.channel().eventLoop().schedule(this.client, this.client.getReconnectTime(), TimeUnit.SECONDS);
        }
*/
    }
}
