package org.holer.server.init;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.ssl.SslHandler;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;

import org.holer.common.util.IdleChecker;
import org.holer.common.util.MsgDecoder;
import org.holer.common.util.MsgEncoder;
import org.holer.common.util.SSLCreator;
import org.holer.server.handler.ServerHandler;

public class ServerInitializer extends ChannelInitializer<SocketChannel> {
    private boolean sslEnabled;
    public ServerInitializer(boolean enabled) {
        this.sslEnabled = enabled;
    }

    protected void initChannel(SocketChannel sc) throws Exception {
        if (this.sslEnabled) {
            SSLContext sslCtx = SSLCreator.getCreator("conf/holer.jks").getSSLContext();
            SSLEngine engine = sslCtx.createSSLEngine();
            engine.setUseClientMode(false);
            engine.setNeedClientAuth(true);
            sc.pipeline().addLast("ssl", new SslHandler(engine));
        }
        sc.pipeline().addLast(new MsgDecoder(2097152, 0, 4, 0, 0));
        sc.pipeline().addLast(new MsgEncoder());
        sc.pipeline().addLast(new IdleChecker(60, 40, 0));
        sc.pipeline().addLast(new ServerHandler());
    }
}
