package net.taehui.twilight.site

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.http.HttpObjectAggregator
import io.netty.handler.codec.http.HttpServerCodec
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler
import net.taehui.twilight.Logger

class SiteBoot(eventLoopGroup: EventLoopGroup, eventChannel: Class<out ServerSocketChannel>) : 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(HttpServerCodec())
                        .addLast(HttpObjectAggregator(Int.MAX_VALUE))
                        .addLast(WebSocketServerCompressionHandler())
                        .addLast(WebSocketServerProtocolHandler("/qwilight/ws", null, true, Int.MAX_VALUE))
                        .addLast(SiteAvatar())
                }
            })
    }

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