package org.framework.lazy.cloud.network.heartbeat.client.netty.tcp.socket;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.client.config.NettyClientProperties;
import org.framework.lazy.cloud.network.heartbeat.client.netty.InternalNetworkClientPermeateServerVisitor;
import org.framework.lazy.cloud.network.heartbeat.client.netty.tcp.filter.NettyTcpClientPermeateServerTransferFilter;
import org.framework.lazy.cloud.network.heartbeat.common.constant.TcpMessageType;
import org.framework.lazy.cloud.network.heartbeat.common.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.adapter.ChannelTypeAdapter;
import org.framework.lazy.cloud.network.heartbeat.common.utils.ChannelAttributeKeyUtils;

import java.util.concurrent.TimeUnit;

/**
 * 客户端渗透服务端传输通道
 */
@Slf4j
public class NettyTcpClientPermeateServerVisitorTransferSocket {
    static EventLoopGroup eventLoopGroup = new NioEventLoopGroup();

    /**
     * 连接服务端通信通道
     * <p>
     * internalNetworkClientPermeateServerVisitor
     */
    public static void buildTransferServer(InternalNetworkClientPermeateServerVisitor internalNetworkClientPermeateServerVisitor, Channel visitorChannel) {

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                // 设置读缓冲区为2M
                .option(ChannelOption.SO_RCVBUF, 2048 * 1024)
                // 设置写缓冲区为1M
                .option(ChannelOption.SO_SNDBUF, 1024 * 1024)
//                .option(ChannelOption.TCP_NODELAY, false)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000 * 60)//连接超时时间设置为 60 秒
//                .option(ChannelOption.SO_BACKLOG, 256)//务端接受连接的队列长度 默认128
//                .option(ChannelOption.RCVBUF_ALLOCATOR, new NettyRecvByteBufAllocator(1024 * 1024))//用于Channel分配接受Buffer的分配器 默认AdaptiveRecvByteBufAllocator.DEFAULT

                .option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(1024 * 1024, 1024 * 1024 * 2))

                .handler(new NettyTcpClientPermeateServerTransferFilter(new ChannelTypeAdapter(internalNetworkClientPermeateServerVisitor.getHandleChannelTypeAdvancedList())))
        ;
        NettyClientProperties nettyClientProperties = internalNetworkClientPermeateServerVisitor.getNettyClientProperties();
        String inetHost = nettyClientProperties.getInetHost();
        int inetPort = nettyClientProperties.getInetPort();
        // local client id

        String clientId = nettyClientProperties.getClientId();

        String targetIp = internalNetworkClientPermeateServerVisitor.getTargetIp();
        Integer targetPort = internalNetworkClientPermeateServerVisitor.getTargetPort();

        String visitorId = ChannelAttributeKeyUtils.getVisitorId(visitorChannel);
        Integer visitorPort = internalNetworkClientPermeateServerVisitor.getVisitorPort();

        // 客户端新建访客通道 连接服务端IP:{},连接服务端端口:{}
        log.debug("Client creates a new visitor channel to connect to server IP: {}, connecting to server port: {}", inetHost, inetPort);
        ChannelFuture future = bootstrap.connect(inetHost, inetPort);

        // 使用的客户端ID:{}
        log.info("Client ID used: {}", clientId);
        future.addListener((ChannelFutureListener) futureListener -> {
            Channel transferChannel = futureListener.channel();
            if (futureListener.isSuccess()) {

                NettyProxyMsg myMsg = new NettyProxyMsg();
                myMsg.setType(TcpMessageType.TCP_REPORT_CLIENT_TRANSFER_SERVER_PERMEATE_CHANNEL_CONNECTION_SUCCESSFUL);
                myMsg.setClientId(clientId);
                myMsg.setVisitorPort(visitorPort);
                myMsg.setClientTargetIp(targetIp);
                myMsg.setClientTargetPort(targetPort);
                myMsg.setVisitorId(visitorId);
                ChannelAttributeKeyUtils.buildVisitorId(transferChannel, visitorId);
                ChannelAttributeKeyUtils.buildClientId(transferChannel, clientId);
                // 传输通道打开后自动读取
                ChannelAttributeKeyUtils.buildNextChannel(visitorChannel, transferChannel);
                ChannelAttributeKeyUtils.buildNextChannel(transferChannel, visitorChannel);

                transferChannel.writeAndFlush(myMsg);

            } else {
                log.warn("客户端渗透服务端通信通道中断....");
                eventLoopGroup.schedule(() -> {
                    try {
                        buildTransferServer(internalNetworkClientPermeateServerVisitor, visitorChannel);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }, 2, TimeUnit.SECONDS);
            }
        });
    }
}