/*
 * *********************************************************************************************************************
 *
 *          !!
 *        .F88X
 *        X8888Y
 *      .}888888N;
 *        i888888N;        .:!              .I$WI:
 *          R888888I      .'N88~            i8}+8Y&8"l8i$8>8W~'>W8}8]KW+8IIN"8&
 *          .R888888I    .;N8888~          .X8'  "8I.!,/8"  !%NY8`"8I8~~8>,88I
 *            +888888N;  .8888888Y                                  "&&8Y.}8,
 *            ./888888N;  .R888888Y        .'}~    .>}'.`+>  i}!    "i'  +/'  .'i~  !11,.:">,  .~]!  .i}i
 *              ~888888%:  .I888888l      .]88~`1/iY88Ii+1'.R$8$8]"888888888>  Y8$  W8E  X8E  W8888'188Il}Y88$*
 *              18888888    E8888881    .]W%8$`R8X'&8%++N8i,8N%N8+l8%`  .}8N:.R$RE%N88N%N$K$R  188,FE$8%~Y88I
 *            .E888888I  .i8888888'      .:$8I;88+`E8R:/8N,.>881.`$8E/1/]N8X.Y8N`"KF&&FK!'88*."88K./$88%RN888+~
 *            8888888I  .,N888888~        ~88i"8W,!N8*.I88.}888%F,i$88"F88"  888:E8X.>88!i88>`888*.}Fl1]*}1YKi'
 *          i888888N'      I888Y          ]88;/EX*IFKFK88X  K8R  .l8W  88Y  ~88}'88E&%8W.X8N``]88!.$8K  .:W8I
 *        .i888888N;        I8Y          .&8$  .X88!  i881.:%888>I88  ;88]  +88+.';;;;:.Y88X  18N.,88l  .+88/
 *      .:R888888I
 *      .&888888I                                          Copyright (c) 2009-2020.  博锐尚格科技股份有限公司
 *        ~8888'
 *        .!88~                                                                     All rights reserved.
 *
 * *********************************************************************************************************************
 */

package com.persagy.server.scheduler.server

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

import com.persagy.proto.MessageProtoStr
import com.persagy.server.scheduler.pojo.ChannelHandlerContextWrapper
import com.persagy.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.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.yaml.snakeyaml.Yaml
import java.util.*
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()
//
//        }
    }

}
