package org.framework.lazy.cloud.network.heartbeat.server.netty.tcp.advanced;

import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Role;
import org.springframework.stereotype.Component;
import org.framework.lazy.cloud.network.heartbeat.common.NettyCommunicationIdContext;
import org.framework.lazy.cloud.network.heartbeat.common.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.NettyRealIdContext;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.tcp.server.AbstractHandleTcpReportServicePermeateClientRealConnectTypeAdvanced;
import org.framework.lazy.cloud.network.heartbeat.common.utils.ChannelAttributeKeyUtils;

/**
 * 服务端渗透客户端通信通道
 */
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
@Slf4j
@Component
public class ServerHandleTcpReportServicePermeateClientRealConnectTypeAdvanced extends AbstractHandleTcpReportServicePermeateClientRealConnectTypeAdvanced<NettyProxyMsg> {

    /**
     * 处理当前数据
     *
     * @param transferChannel       当前通道
     * @param nettyProxyMsg 通道数据
     */
    @Override
    protected void doHandler(Channel transferChannel, NettyProxyMsg nettyProxyMsg) {
        // 客户端绑定端口成功
        byte[] clientId = nettyProxyMsg.getClientId();
        byte[] clientTargetIp = nettyProxyMsg.getClientTargetIp();
        byte[] clientTargetPort = nettyProxyMsg.getClientTargetPort();
        byte[] visitorPort = nettyProxyMsg.getVisitorPort();
        byte[] visitorId = nettyProxyMsg.getVisitorId();
        log.info("客户端:{},绑定真实服务ip:{},port:{},成功", new String(clientId), new String(clientTargetIp), new String(clientTargetPort));
        // 绑定服务端访客通信通道
        NettyCommunicationIdContext.pushVisitor(transferChannel, new String(visitorId));
        ChannelAttributeKeyUtils.buildVisitorId(transferChannel, visitorId);
        ChannelAttributeKeyUtils.buildClientId(transferChannel, clientId);
        ChannelAttributeKeyUtils.buildVisitorPort(transferChannel, Integer.valueOf(new String(visitorPort)));
        // 访客通道开启自动读取
        Channel visitorRealChannel = NettyRealIdContext.getReal(visitorId);
        visitorRealChannel.config().setOption(ChannelOption.AUTO_READ, true);

        ChannelAttributeKeyUtils.buildNextChannel(transferChannel, visitorRealChannel);
        ChannelAttributeKeyUtils.buildNextChannel(visitorRealChannel, transferChannel);

        // 或许此处还应该通知服务端 这个访客绑定的客户端真实通道打开

        // 下发客户端 真实通道自动读写开启


    }
}
