package cn.sagacloud.server.scheduler.pojo


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

import java.util.HashMap

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()
            }
        }
        var jsonInfo = JSONObject.parseObject(toBeSent.param)
        jsonInfo["FloorServerUrl"] = toBeSent.floorServerUrl
        jsonInfo["UseablePhaseName"] = toBeSent.useablePhaseName
        jsonInfo["SagaSign"] = toBeSent.sagaSign
        jsonInfo["CheckItems"] = toBeSent.checkItems
        jsonInfo["FacilityParameters"] = toBeSent.facilityParameters
        jsonInfo["SpaceParameters"] = toBeSent.spaceParameters
        jsonInfo["RoomParameters"] = toBeSent.roomParameters
        jsonInfo["MEPCurveParameters"] = toBeSent.mEPCurveParameters
        jsonInfo["EquipComponentCode"] = toBeSent.equipComponentCode
        toBeSent.param = jsonInfo.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)
    }
}
