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

import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.client.config.NettyClientProperties;
import org.framework.lazy.cloud.network.heartbeat.client.netty.udp.socket.NettyUdpServerPermeateClientRealSocket;
import org.framework.lazy.cloud.network.heartbeat.common.InternalNetworkPenetrationRealClient;
import org.framework.lazy.cloud.network.heartbeat.common.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.HandleChannelTypeAdvanced;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.udp.client.AbstractHandleUdpDistributeServicePermeateClientRealConnectTypeAdvanced;
import org.wu.framework.spring.utils.SpringContextHolder;

import java.util.ArrayList;
import java.util.List;

/**
 * 客户端创建真实代理同奥
 */
@Slf4j
public class ClientHandleUdpDistributeServicePermeateClientRealConnectTypeAdvanced extends AbstractHandleUdpDistributeServicePermeateClientRealConnectTypeAdvanced<NettyProxyMsg> {

    private final NettyClientProperties nettyClientProperties;// 服务端地址信息


    public ClientHandleUdpDistributeServicePermeateClientRealConnectTypeAdvanced(NettyClientProperties nettyClientProperties) {
        this.nettyClientProperties = nettyClientProperties;
    }

    /**
     * 处理当前数据
     *
     * @param channel 当前通道
     * @param msg     通道数据
     */
    @Override
    protected void doHandler(Channel channel, NettyProxyMsg msg) {
        // 创建真实端口监听
        byte[] clientIdBytes = msg.getClientId();
        byte[] visitorPort = msg.getVisitorPort();
        byte[] clientTargetIp = msg.getClientTargetIp();
        byte[] clientTargetPort = msg.getClientTargetPort();
        byte[] visitorIdBytes = msg.getVisitorId();
        InternalNetworkPenetrationRealClient internalNetworkPenetrationRealClient =
                InternalNetworkPenetrationRealClient
                        .builder()
                        .clientId(new String(clientIdBytes))
                        .visitorPort(Integer.valueOf(new String(visitorPort)))
                        .clientTargetIp(new String(clientTargetIp))
                        .clientTargetPort(Integer.valueOf(new String(clientTargetPort)))
                        .visitorId(new String(visitorIdBytes))
                        .build();

        List<HandleChannelTypeAdvanced> handleChannelTypeAdvancedList = new ArrayList<>(SpringContextHolder.getApplicationContext().getBeansOfType(HandleChannelTypeAdvanced.class).values());
        // 绑定真实服务端口
        NettyUdpServerPermeateClientRealSocket.buildRealServer(internalNetworkPenetrationRealClient, nettyClientProperties, handleChannelTypeAdvancedList);

    }
}
