package net.taehui.twilight.taehui

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.HttpClientCodec
import io.netty.handler.codec.http.HttpObjectAggregator
import io.netty.handler.codec.http.HttpServerCodec
import net.taehui.twilight.Logger

class TaehuiBoot(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(HttpClientCodec())
                        .addLast(TaehuiAvatar())
                }
            })
    }

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