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

import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.common.*;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.tcp.server.AbstractHandleTcpReportClientTransferClientPermeateChannelConnectionSuccessfulTypeAdvanced;
import org.framework.lazy.cloud.network.heartbeat.common.constant.TcpMessageType;
import org.framework.lazy.cloud.network.heartbeat.common.utils.ChannelAttributeKeyUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Role;
import org.springframework.stereotype.Component;

/**
 * 上报 客户端渗透客户端数据传输通道连接成功
 */
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
@Slf4j
@Component
public class ServerHandleTcpReportClientTransferClientPermeateChannelConnectionSuccessfulTypeAdvanced extends AbstractHandleTcpReportClientTransferClientPermeateChannelConnectionSuccessfulTypeAdvanced<NettyProxyMsg> {
    /**
     * 处理当前数据
     *
     * @param transferChannel       当前通道
     * @param nettyProxyMsg 通道数据
     */
    @Override
    protected void doHandler(Channel transferChannel, NettyProxyMsg nettyProxyMsg) {
        // 创建目标地址连接
        byte[] msgVisitorId = nettyProxyMsg.getVisitorId();
        byte[] msgVisitorPort = nettyProxyMsg.getVisitorPort();
        byte[] msgClientTargetIp = nettyProxyMsg.getClientTargetIp();
        byte[] msgClientTargetPort = nettyProxyMsg.getClientTargetPort();
        byte[] clientId = nettyProxyMsg.getClientId();// 目标客户端ID

        ChannelAttributeKeyUtils.buildClientId(transferChannel, clientId);
        ChannelAttributeKeyUtils.buildVisitorPort(transferChannel, Integer.parseInt(new String(msgVisitorPort)));
        ChannelAttributeKeyUtils.buildVisitorId(transferChannel, msgVisitorId);
        // 绑定访客通道
        NettyTransferChannelContext.pushVisitor(transferChannel,msgVisitorId);
        Channel clientChannel = ChannelContext.getLoadBalance(clientId);

        NettyProxyMsg clientConnectTagetNettyProxyMsg = new NettyProxyMsg();
        clientConnectTagetNettyProxyMsg.setVisitorId(msgVisitorId);
        clientConnectTagetNettyProxyMsg.setVisitorPort(msgVisitorPort);
        clientConnectTagetNettyProxyMsg.setClientTargetIp(msgClientTargetIp);
        clientConnectTagetNettyProxyMsg.setClientTargetPort(msgClientTargetPort);
        clientConnectTagetNettyProxyMsg.setClientId(clientId);
        clientConnectTagetNettyProxyMsg.setType(TcpMessageType.TCP_DISTRIBUTE_CLIENT_TRANSFER_CLIENT_PERMEATE_CHANNEL_CONNECTION_SUCCESSFUL);
        if (clientChannel != null) {
            clientChannel.writeAndFlush(clientConnectTagetNettyProxyMsg);
        }else {
            log.error("can not find the client:【】 channel",clientId);
        }



    }
}
