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


import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.common.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.tcp.client.AbstractHandleTcpDistributeClientPermeateServerTransferTypeAdvanced;
import org.framework.lazy.cloud.network.heartbeat.common.enums.TcpMessageTypeEnums;
import org.framework.lazy.cloud.network.heartbeat.common.utils.ChannelAttributeKeyUtils;


/**
 * 服务端处理客户端数据传输
 *
 * @see TcpMessageTypeEnums#TCP_DISTRIBUTE_CLIENT_TRANSFER
 */
@Slf4j
public class ClientHandleTcpDistributeClientPermeateServerTransferTypeAdvanced extends AbstractHandleTcpDistributeClientPermeateServerTransferTypeAdvanced<NettyProxyMsg> {


    /**
     * 处理当前数据
     *
     * @param channel       当前通道
     * @param nettyProxyMsg 通道数据
     */
    @Override
    public void doHandler(Channel channel, NettyProxyMsg nettyProxyMsg) {
        log.debug("客户端渗透服务端返回数据:{}" , new String(nettyProxyMsg.getData()));
        byte[] visitorPort = nettyProxyMsg.getVisitorPort();
        byte[] clientTargetIp = nettyProxyMsg.getClientTargetIp();
        byte[] clientTargetPort = nettyProxyMsg.getClientTargetPort();
        byte[] visitorId = nettyProxyMsg.getVisitorId();
        // 真实服务通道
//        Channel realChannel = NettyRealIdContext.getReal(new String(visitorId));
        Channel nextChannel = ChannelAttributeKeyUtils.getNextChannel(channel);
        if (nextChannel == null) {
            log.error("无法获取访客:{} 真实服务", new String(visitorId));
            return;
        }


        // 把数据转到真实服务
        ByteBuf buf = channel.config().getAllocator().buffer(nettyProxyMsg.getData().length);
        buf.writeBytes(nettyProxyMsg.getData());

        nextChannel.writeAndFlush(buf);

    }

}
