/*
 * *********************************************************************************************************************
 *
 *          !!
 *        .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.proto.MessageUtil
import com.persagy.server.scheduler.pojo.ChannelHandlerContextWrapper
import com.persagy.server.scheduler.pojo.ClientMessage
import com.persagy.server.scheduler.pojo.Command
import com.persagy.server.scheduler.pojo.TaskStatus
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInboundHandlerAdapter
import java.util.*
import java.util.concurrent.ConcurrentHashMap

class SchedulerHandler(internal var clientList: ArrayList<ChannelHandlerContextWrapper>) : ChannelInboundHandlerAdapter() {
    private var ctxw: ChannelHandlerContextWrapper? = null

    /**
     * 刚添加上handler的时候    1
     * @param ctx
     */
    override fun handlerAdded(ctx: ChannelHandlerContext?) {
        //SocketAddress addr = ctx.channel().remoteAddress();
        println("client incoming")
    }

    /**
     * 客户端活动状态         2
     * @param ctx
     */
    override fun channelActive(ctx: ChannelHandlerContext) {
        ctxw = ChannelHandlerContextWrapper(ctx)
        this.clientList.add(ctxw!!)
        ctx.channel().writeAndFlush(MessageUtil.buildMessage(Command.ClientInfo.name, "", ""))
    }

    /**
     * 客户端服务器互发消息      3
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Throws(Exception::class)
    override fun channelRead(ctx: ChannelHandlerContext, msg: Any) {
        try {
            // Do something with msg
            val message = msg as MessageProtoStr.Message
            MessageHandler.offer(ClientMessage(ctxw, message))
            ctx.channel().writeAndFlush(MessageUtil.buildMessage(Command.HeartBeat.name, "", ""))
        } catch (e : Exception){
            println("Read Exception : ${e.message}")
        }finally {
            // 如果ctx write 或 writeAndFlush过的话, 就不用释放msg
            //ReferenceCountUtil.release(msg);
        }
    }

    /**
     * 客户端异常原因  4
     * @param ctx
     * @param cause
     */
    override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) {
        println("client exceptionCaught : " + cause.message)
    }

    /**
     * 客户端非活动状态  5
     * @param ctx
     */
    override fun channelInactive(ctx: ChannelHandlerContext) {
        println("client channelInactive")
    }

    /**
     * 客户端断开连接 6
     * @param ctx
     */
    override fun handlerRemoved(ctx: ChannelHandlerContext?) {
        this.clientList.remove(ctxw)
        try {
            for (i in ctxw!!.taskSendingStatusMap){
                if(DispatchTask.tasks!!.containsKey(i.key))
                    DispatchTask.tasks!![i.key]!!.status = 0;
            }
        }catch (e : Exception){}
    }

    companion object {
        // Map<当前状态, Map<可接受的命令, 接受完命令后的状态>>
        var statusTransitionMap: MutableMap<TaskStatus, Map<Command, TaskStatus>> = ConcurrentHashMap()

        init {
            val waitingMap = HashMap<Command, TaskStatus>()
            val sendingMap = HashMap<Command, TaskStatus>()
            val sentMap = HashMap<Command, TaskStatus>()
            val fileDownloadExceptionMap = HashMap<Command, TaskStatus>()
            val commandExceptionMap = HashMap<Command, TaskStatus>()
            statusTransitionMap[TaskStatus.Waiting] = waitingMap//CommonUtil.createSet(Command.TaskSuccess));
            statusTransitionMap[TaskStatus.Sending] = sendingMap//CommonUtil.createSet(Command.AcceptTask, Command.RefuseTask, Command.TaskSuccess));
            statusTransitionMap[TaskStatus.Sent] = sentMap//CommonUtil.createSet(Command.CommandError, Command.DownloadError, Command.TaskSuccess));
            statusTransitionMap[TaskStatus.FileDownloadException] = fileDownloadExceptionMap//CommonUtil.createSet(Command.TaskSuccess));
            statusTransitionMap[TaskStatus.CommandExecuteException] = commandExceptionMap//CommonUtil.createSet(Command.TaskSuccess));
            statusTransitionMap[TaskStatus.Finished] = HashMap()

            waitingMap[Command.TaskSuccess] = TaskStatus.Finished
            waitingMap[Command.DownloadError] = TaskStatus.FileDownloadException
            waitingMap[Command.CommandError] = TaskStatus.CommandExecuteException
            waitingMap[Command.AcceptTask] = TaskStatus.Sent

            sendingMap[Command.AcceptTask] = TaskStatus.Sent
            sendingMap[Command.RefuseTask] = TaskStatus.Waiting
            sendingMap[Command.TaskSuccess] = TaskStatus.Finished
            sendingMap[Command.DownloadError] = TaskStatus.FileDownloadException
            sendingMap[Command.CommandError] = TaskStatus.CommandExecuteException

            sentMap[Command.TaskSuccess] = TaskStatus.Finished
            sentMap[Command.DownloadError] = TaskStatus.FileDownloadException
            sentMap[Command.CommandError] = TaskStatus.CommandExecuteException

            fileDownloadExceptionMap[Command.TaskSuccess] = TaskStatus.Finished
            commandExceptionMap[Command.TaskSuccess] = TaskStatus.Finished
        }
    }
}
