package org.framework.lazy.cloud.network.heartbeat.server.netty.udp.filter;

import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.common.InternalNetworkServerPermeateServerRealServer;
import org.framework.lazy.cloud.network.heartbeat.common.decoder.TransferDecoder;
import org.framework.lazy.cloud.network.heartbeat.common.encoder.TransferEncoder;
import org.framework.lazy.cloud.network.heartbeat.common.filter.DebugChannelInitializer;
import org.framework.lazy.cloud.network.heartbeat.server.netty.udp.handler.NettyUdpServerPermeateServerRealHandler;

@Slf4j
public class NettyUdpServerPermeateServerRealFilter extends DebugChannelInitializer<SocketChannel> {
    private final InternalNetworkServerPermeateServerRealServer internalNetworkServerPermeateServerRealServer;

    public NettyUdpServerPermeateServerRealFilter(InternalNetworkServerPermeateServerRealServer internalNetworkServerPermeateServerRealServer) {
        this.internalNetworkServerPermeateServerRealServer = internalNetworkServerPermeateServerRealServer;
    }

    /**
     * This method will be called once the {@link Channel} was registered. After the method returns this instance
     * will be removed from the {@link ChannelPipeline} of the {@link Channel}.
     *
     * @param ch the {@link Channel} which was registered.
     */
    @Override
    protected void initChannel0(SocketChannel ch) {
        ChannelPipeline pipeline = ch.pipeline();
        Boolean isSsl = internalNetworkServerPermeateServerRealServer.getIsSsl();
        if(isSsl!=null && isSsl) {
            log.info("init channel0 ssl");
            String targetIp = internalNetworkServerPermeateServerRealServer.getClientTargetIp();
            Integer targetPort = internalNetworkServerPermeateServerRealServer.getClientTargetPort();
            // 适配https
            try {
                SslContext sslContext = SslContextBuilder.forClient()
                        .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
                pipeline.addLast(sslContext.newHandler(ch.alloc()));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        // 解码、编码
        pipeline.addLast(new TransferDecoder(Integer.MAX_VALUE, 1024 * 1024*10));
        pipeline.addLast(new TransferEncoder());
        pipeline.addLast(new NettyUdpServerPermeateServerRealHandler());

    }
}