package net.taehui.twilight.qwilight

import io.netty.bootstrap.ServerBootstrap
import io.netty.channel.ChannelInitializer
import io.netty.channel.EventLoopGroup
import io.netty.channel.socket.ServerSocketChannel
import io.netty.channel.socket.SocketChannel
import io.netty.handler.codec.protobuf.ProtobufDecoder
import io.netty.handler.codec.protobuf.ProtobufEncoder
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender
import io.netty.handler.ssl.SslHandler
import net.taehui.twilight.Logger
import javax.net.ssl.SSLContext

class QwilightBoot(
    eventLoopGroup: EventLoopGroup,
    eventChannel: Class<out ServerSocketChannel>,
    sslContext: SSLContext
) : Logger, Runnable {
    private val mainBootstrap: ServerBootstrap

    init {
        mainBootstrap = ServerBootstrap().group(eventLoopGroup).channel(eventChannel)
            .childHandler(object : ChannelInitializer<SocketChannel>() {
                public override fun initChannel(ch: SocketChannel) {
                    ch.pipeline()
                        .addLast(SslHandler(sslContext.createSSLEngine().apply {
                            useClientMode = false
                        }))
                        .addLast(ProtobufVarint32FrameDecoder())
                        .addLast(ProtobufDecoder(EventOuterClass.Event.getDefaultInstance()))
                        .addLast(ProtobufVarint32LengthFieldPrepender())
                        .addLast(ProtobufEncoder())
                        .addLast(QwilightAvatar())
                }
            })
    }

    override fun run() {
        logInfo("Loading Qwilight")
        mainBootstrap.bind(6101).channel().closeFuture()
            .addListener { logInfo("Closed Qwilight") }
    }
}