/*
 * *********************************************************************************************************************
 *
 *          !!
 *        .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.pojo

import cn.sagacloud.server.DispatchTask
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.persagy.proto.MessageProtoStr
import com.persagy.proto.MessageUtil
import com.persagy.server.scheduler.models.TaskEntity
import com.persagy.server.scheduler.utils.CommonUtil
import io.netty.channel.ChannelHandlerContext
import org.apache.log4j.Logger
import java.util.*

class ChannelHandlerContextWrapper(val ctx: ChannelHandlerContext) { // 通信handler
    var lastRejectTime: Long = 0
        private set        // unix时间片, 精确到秒
    private val sendingTimeOut: Long = 15            // 发送给客户端任务, 如果超过该时间未响应, 则超时, 并将发送的任务状态置为初始状态
    private val lastRefuseTimeOut: Long = 90       // 如果客户端拒绝任务, 则等待lastRefuseTimeOut秒, 才会再分配任务给该客户端
    var clientInfo: String? = null             // mac地址
    // 任务发送中状态map,     key --> taskid, value --> 发送任务时间点,    如果超过15s, 即为超时.
    public val taskSendingStatusMap = HashMap<String, Long>()
    companion object {
        private val log = Logger.getLogger(ChannelHandlerContextWrapper::class.java)
    }
    /**
     * 获取一个在发送任务时超时的任务id
     * @return 任务id
     */
    val oneSendingTimeOutTaskId: String?
        get() {
            if (taskSendingStatusMap.size == 0)
                return null
            val currentTime = CommonUtil.time
            for (id in taskSendingStatusMap.keys) {
                val sentTime = taskSendingStatusMap[id]
                if (currentTime - sentTime!! > sendingTimeOut) {
                    return id
                }
            }
            return null
        }

    val isLastRefuseTimeOutPassed: Boolean
        get() {
            if (lastRejectTime == 0L)
                return true
            val currentTime = CommonUtil.time
            return if (currentTime - lastRefuseTimeOut > lastRejectTime) true else false
        }

    init {
        this.lastRejectTime = 0
        clientInfo = null
    }

    fun sendTask(toBeSent: TaskEntity) {
        if (ctx.channel().isActive) {
            log.info("task : ${toBeSent.id}, dest : $clientInfo")
            val content = buildContent(toBeSent)
            val msg = MessageUtil.buildMessage(Command.SendTask.name, toBeSent.id!!, content)
            ctx.writeAndFlush(msg)
            toBeSent.status = 1
            taskSendingStatusMap[toBeSent.id!!] = CommonUtil.time
        }
    }

    private fun buildContent(toBeSent: TaskEntity): String? {
        if(toBeSent.param == null || toBeSent.param!!.isEmpty()){
            var param = JSONObject()
            param["MBIName"] = toBeSent.projectId
            param["ModelId"] = toBeSent.modelId
            toBeSent.param = param.toString()
        }else{
            try {
                var jsonInfo = JSONObject.parseObject(toBeSent.param)
                if(jsonInfo == null)
                    jsonInfo = JSONObject()
                if(!jsonInfo.containsKey("ProjectId"))
                    jsonInfo["ProjectId"] = toBeSent.projectId
                if(!jsonInfo.containsKey("ModelId"))
                    jsonInfo["ModelId"] = toBeSent.modelId
                toBeSent.param = jsonInfo.toString()
            }catch (e : Exception){
                var param = JSONObject()
                param["ProjectId"] = toBeSent.projectId
                param["ModelId"] = toBeSent.modelId
                param["Info"] = toBeSent.param
                toBeSent.param = param.toString()
            }
        }
        return JSON.toJSONString(toBeSent)
    }


    fun resetSendingTimeOutTask(id: String?) {
        if (id != null) {
            taskSendingStatusMap.remove(id)
        }
    }

    /**
     * 设置上次被拒绝任务时间
     */
    fun setLastRejectTime(taskId: String) {
        this.lastRejectTime = CommonUtil.time
        DispatchTask.changeStatusByCmd(taskId, Command.RefuseTask, clientInfo!!)
    }

    /**
     * 接受任务
     */
    fun acceptTask(taskId: String) {
        DispatchTask.isAllowCmd(taskId, Command.AcceptTask) ?: return
        DispatchTask.changeStatusByCmd(taskId, Command.AcceptTask, clientInfo!!)
        taskSendingStatusMap.remove(taskId)
    }

    /**
     * 客户端成功完成任务
     */
    fun taskSuccess(message: MessageProtoStr.Message) {
        DispatchTask.changeStatusByCmdWithReturnJson(message.taskId, Command.TaskSuccess, clientInfo!!, message.content)
    }

    /**
     * 因为命令错误, 执行异常未完成任务
     */
    fun commandError(message: MessageProtoStr.Message) {
        DispatchTask.changeStatusByCmdWithReturnJson(message.taskId, Command.CommandError, clientInfo!!, message.content)
    }

    /**
     * 客户端因为下载模型失败导致任务失败
     */
    fun downloadError(message: MessageProtoStr.Message) {
        DispatchTask.changeStatusByCmdWithReturnJson(message.taskId, Command.DownloadError, clientInfo!!, message.content)
    }
}
