package com.cisdi.data.XRFRIGHT.impl;

import com.cisdi.data.sdk.enums.ByteOrder;
import com.cisdi.data.sdk.gateway.netty.SessionFactory;
import com.cisdi.data.sdk.gateway.netty.impl.AbstractChannelInitializer;
import com.cisdi.data.sdk.gateway.netty.impl.AbstractIoChannelHandler;
import com.cisdi.data.sdk.gateway.netty.impl.DefaultIoChannelHandler;
import com.cisdi.data.sdk.utils.NettySslUtils;
import com.cisdi.data.sdk.vo.SslConfigVo;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

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

/**
 * @author cuianbing
 * @version 1.0
 * @description: TODO
 * @date 2021/7/7 18:57
 */
@Slf4j
public class XRFRightChannelInitializer<I> extends AbstractChannelInitializer<I> {

    private SessionFactory factory;
    private ByteOrder byteOrder;
    private SslConfigVo sslConfigVo;


    /**
     * 构造通道初始化器对象
     * @param factory 会话工厂
     * @param byteOrder 大小端
     * @param sslConfig ssl证书配置，如果不启用tls，传null
     */
    public XRFRightChannelInitializer(SessionFactory factory,
                                      ByteOrder byteOrder,
                                      SslConfigVo sslConfig) {
        this.factory = factory;
        this.byteOrder = byteOrder;
        this.sslConfigVo = sslConfig;
    }

    @Override
    protected AbstractIoChannelHandler<I> getTailHandler() {
        return new DefaultIoChannelHandler(factory);
    }

    @Override
    protected List<ChannelHandler> getHandlers() {
        List<ChannelHandler> handlers = new ArrayList<ChannelHandler>();
        return handlers;
    }

    @Override
    protected IdleStateHandler getIdleStateHandler() {
        return new IdleStateHandler(15, 15, 30);
    }

    @Override
    protected ChannelHandler getSslChannelHandler(Channel socketChannel) {
        ChannelHandler sslHandler = null;
        try {
            if(sslConfigVo != null) {
                sslHandler = NettySslUtils.getServerSslHandler((SocketChannel)socketChannel, sslConfigVo);
            }
        } catch (Exception e) {
            log.warn(e.getLocalizedMessage(), e);
        }
        return sslHandler;
    }
}
