package cn.sagacloud.server

/*
 * Author: Jxing
 * Create Time: 2019/3/20
 */


import cn.sagacloud.proto.MessageProtoStr
import cn.sagacloud.server.scheduler.pojo.ChannelHandlerContextWrapper
import cn.sagacloud.server.scheduler.pojo.Config
import io.netty.bootstrap.ServerBootstrap
import io.netty.channel.Channel
import io.netty.channel.ChannelInitializer
import io.netty.channel.ChannelOption
import io.netty.channel.ChannelPipeline
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioServerSocketChannel
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 org.apache.log4j.Logger
import org.springframework.stereotype.Component
import org.yaml.snakeyaml.Yaml

import java.util.ArrayList
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors


class Server @Throws(Exception::class)
constructor() {
    internal var bootstrap = ServerBootstrap()
    private val acceptGroup = NioEventLoopGroup()
    private val workerGroup = NioEventLoopGroup()
    private var channel: Channel? = null
    internal var config: Config
    internal var dispatchTask: DispatchTask
    internal var messageHandler: MessageHandler
    internal var clientList = ArrayList<ChannelHandlerContextWrapper>()

    init {
        // 初始化serverSocket
        bootstrap.group(acceptGroup, workerGroup)
                .channel(NioServerSocketChannel::class.java)
                .option(ChannelOption.SO_BROADCAST, true)
                .childHandler(object : ChannelInitializer<SocketChannel>() {
                    @Throws(Exception::class)
                    override fun initChannel(ch: SocketChannel) {
                        val pipeline = ch.pipeline()
                        pipeline.addLast(ProtobufVarint32FrameDecoder())
                        // 设置解码
                        pipeline.addLast("decoder", ProtobufDecoder(MessageProtoStr.Message.getDefaultInstance()))
                        pipeline.addLast(ProtobufVarint32LengthFieldPrepender())
                        // 设置编码
                        pipeline.addLast("encoder", ProtobufEncoder())
                        pipeline.addLast(SchedulerHandler(clientList))

                    }
                })
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
        // 初始化配置
        log.info("reading config file...开始读取配置文件...")
        config = Yaml().loadAs(Server::class.java.getClassLoader().getResourceAsStream("config.yml"), Config::class.java)
        log.info("config file read success...读取配置文件完毕...")
        // 初始化Task(从sql到内存)
        log.info("syncing tasks...开始同步数据库中任务...")
        dispatchTask = DispatchTask(clientList)
        messageHandler = MessageHandler()
    }

    @Throws(InterruptedException::class)
    fun start() {
        try {
            // 启动服务
            log.info("listening...开始启动监听...")
            channel = bootstrap.bind(config.port).sync().channel()
            log.info("dispatching...开始分发任务...")
            pool.submit(dispatchTask)        // 开启任务分发线程
            pool.submit(messageHandler)      // 开启消息处理线程
            //pool.submit()
            log.info("server started...服务器启动完毕")
            channel!!.closeFuture().sync()
        } finally {
            workerGroup.shutdownGracefully()
            acceptGroup.shutdownGracefully()
        }
    }

    companion object {
        var pool = Executors.newFixedThreadPool(8)
        private val log = Logger.getLogger(Server::class.java)

//        @Throws(Exception::class)
//        @JvmStatic
//        fun main(args: Array<String>) {
//            //        int port = 6666;
//            //        if (args.length > 0) {
//            //            port = Integer.parseInt(args[0]);
//            //        }
//            Server().start()
//
//        }
    }

}
